Question:

In a project separated from the front and back ends, the data returned by the back end is often too long, and when the front end gets the data, the data is inaccurate and the accuracy is lost.

The range of integers that JavaScript can accurately represent is between -2^53 and 2^53 (excluding both endpoints), beyond which the value cannot be accurately represented.

Here’s an example:

Math.pow(2, 53) // 9007199254740992`

9007199254740992 // 9007199254740992`

9007199254740993 // 9007199254740992`

 

Math.pow(2, 53) === Math.pow(2, 53) + 1 // true
Copy the code

In the above code, after 2 to the power of 53, a number becomes imprecise.

ES6 introduced MAX_SAFE_INTEGER, which represents the largest value in JS. A larger value is Infinity, as opposed to number.min_value

Data processing solutions for projects with front and rear end separation:

The data returned from the backend is typically a string in JSON format, ‘{” ID “:900719925474099122}’.

Axios library source code parsing reference: segmentfault.com/a/119000001…

The axios library that is generally introduced internally uses json.parse () to convert the data returned by the back end into JavaScript objects to make it easier for us to work with the data.

As you can see, ids that are outside the safe integer range are not accurately represented, and this problem is not the fault of Axios.

Solution:

1. Introduce json-bigint

// Json-bigint can handle data that is outside the JavaScript safe integer range

const jsonStr = ‘{ “id”:900719925474099122}’

Console.log (jsonbig.parse (jsonStr)) // Convert the JSON format string to a JavaScript object

// Convert BigNumber to string to use

  console.log(JSONBig.parse(jsonStr).id.toString()) //  900719925474099122

2. Override Axios’s transformResponse method

import JSONBig from 'json-bigint' const JSONbigString = JSONBig({ storeAsString: true}) axiosInstance.defaults.transformResponse = [(data) => { try { return JSONbigString.parse(data) } catch (error) { Return data}}] // Options. StoreAsString, Boolean, default: false // Specifies whether BigInts should be stored in an object as a string, instead of the default BigNumber. // Note that this is dangerous behavior because it breaks the default function of converting back without changing the data type (since this converts all Bigints to be-and-stay strings).Copy the code