Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • Y011-后端返回大数作为唯一id精度失真

Y011-后端返回大数作为唯一id精度失真

后端返回大数作为唯一id精度失真问题

response 返回的结果跟实际的不一致

最好是后端返回字符串类型

实在不行 可以在前端进行处理

方案1:正则替换


如果我们使用的是axios请求数据,Axios 提供了自定义处理原始后端返回数据的 API:transformResponse , 可以这样处理:
复制代码axios({  
method: method,  
url: url,  
data: data,  
transformResponse: [function (data) {  
    // 将Long类型数据转换为字符串
    const convertedJsonString = data.replace(/"(\w+)":(\d{15,})/g, '"$1":"$2"'); 
    return JSON.parse(convertedJsonString);  
}],  
})


// 假设后端返回的JSON数据如下:
const responseData = {
  id: 12345678901234567890, // 这是一个Long类型数据
  name: "John Doe"
};

// 处理过的json数据
console.log(responseData.id); // 这将输出字符串:"12345678901234567890"
console.log(typeof responseData.id); // 这将输出 "string"


方案2:我们可以借助json-bigint这个第三方包来处理。

import JSONbig from "json-bigint";
    axios({  
    method: method,  
    url: url,  
    data: data,  
    transformResponse: [function (data) {  
+        const JSONbigToString = JSONbig({ storeAsString: true });
+          // 将Long类型数据转换为字符串
+          return JSONbigToString.parse(data);  
    }],  
    })
    
    
    // 假设后端返回的JSON数据如下:
    const responseData = {
      id: 12345678901234567890, // 这是一个Long类型数据
      name: "John Doe"
    };
    
    // 处理过的json数据
    console.log(responseData.id); // 这将输出字符串:"12345678901234567890"
    console.log(typeof responseData.id); // 这将输出 "string"


Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人