The problem of loss of precision when the back-end Long type is passed to the front-end

The problem arises: the id attribute of the Java Bean on the backend uses the Long type and corresponds to the database primary key using the bigint type. When the data is passed to the frontend using JSON, the end of the data received by the frontend will become 0. (The problem of precision loss occurred)
The cause of the problem: the range that long in Java can represent is larger than number in js, which means that some values ​​cannot be stored in js (becoming inaccurate values), resulting in the last few digits of Id directly becoming 0.
 

 

 The front end receives and prints:

 Solution 1 (Backend) : Change the id of the backend to a string type, and the frontend will receive it as a string without loss of precision


Solution 2 (front-end) : Front-end solution 1 introduces json-bigint at the front-end,

   npm install json-bigint

Solution 3 (front end) : Where axios is encapsulated , transformResponse allows modification of the response data before passing it to then/catch.

 Modify the source code of axios, find transformResponse in node_modules/axios/lib/default.js and change its content to:

transformResponse: [function transformResponse(data) {
    /*eslint no-param-reassign:0*/
    if (typeof data === 'string') {
      try {
        data = JSON.parse(data);
      } catch (e) { /* Ignore */ }
    }
    return data;
  }],

Solution 4 (Frontend):

When the background is transmitted to the foreground, the Long type data is converted to String type. You can directly manipulate the returned object data, toString() the long type data. (recommend)

Guess you like

Origin blog.csdn.net/weixin_43923808/article/details/131770665