Backend code
// 后端返回的是 JSON 格式的字符串,字符串中的数字超出了 2 的 53 次方,即大数字
require('http')
.createServer((req, res) => {
// exceed Math.pow(2, 53)
res.end('{"id": 900719925474099288}');
})
.listen(3000, () => console.log('Server running on http://localhost:3000'));
Front-end code
Problem: When the front-end uses the axios request interface to get data, it finds that the data it gets is different from that returned by the back-end. The code is as follows:
const axios = require('axios');
const request = axios.create({
baseURL: 'http://localhost:3000',
});
request.get('/').then(({
data }) => {
console.log(data); // { id: 900719925474099300 }
});
The reason: axios internal data would be returned by the backend JSON.parse
operations, but JSON.parse
is not handle large numbers of
solution
const axios = require('axios');
const JSONBIGINT = require('json-bigint');
const request = axios.create({
baseURL: 'http://localhost:3000',
transformResponse: [
data => {
try {
return JSONBIGINT.parse(data);
} catch (err) {
return data;
}
},
],
});
request.get('/').then(({
data }) => {
console.log(JSONBIGINT.stringify(data));
});