后端返回数据中数字太大导致精度丢失问题解决方案

3,927 阅读1分钟

主要原因是后端返回结果中的数字超出了 JavaScript 的数字安全范围。使用 json-bigint 可以解决这个问题。

在 axios 中使用 json-bigint 处理返回结果

  1. 下载
npm i json-bigint
  1. 定制 axios 配置项 transformResponse 处理返回结果
import axios from 'axios'
import JSONbig from 'json-bigint'

const request = axios.create({
  // ... 其它配置
  
  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data
    return JSONbig.parse(data)
  }],
  
  // ... 其它配置
})