背景:
服务端返回的Long类型数据,在chrome里的调试工具response和preview两种状态显示数值不同(例:‘230905010000000743‘, 前端会展示为’230905010000000740’)
原因:
response中的看到的数据格式其实是字符串,preview其实是用了JSON.Parse(字符串) 给我们做美化(格式化),由于前端JS对Long类型支持的精度不够,导致后端使用的Long传到前端丢失精度。
解决方法:
1. axios
import axios from "axios"
import JsonBigint from 'json-bigint'
const http = axios.create({
baseURL: 'http:// www.xxxxx.com',
transformResponse: [
function (data) {
try {
// 如果转换成功则返回转换的数据结果
return JsonBigint.parse(data)
} catch (err) {
// 如果转换失败,则包装为统一数据格式并返回
return data
}
},
],
})
2. fetch
import JsonBigint from 'json-bigint'
fetch(url,options).then((res)=>{
//处理http响应
const _res = await res.text()
return JsonBigint.parse(_res)
},(error)=>{
//处理错误
})