【问题标题】:axios - how to deal with big integersaxios - 如何处理大整数
【发布时间】:2017-10-02 22:02:19
【问题描述】:

这是我的要求:

    axios.get(url)
    .then(res => {
        console.log(res.data)
    })

输出为{ value: 156144277082605255 }

但应该是{ value: 156144277082605250 }

在这种情况下如何处理大整数? 我尝试使用json-bigint 但由于我从 axios 获取 response.data 作为对象 - 它没有帮助。

【问题讨论】:

    标签: javascript axios bigint


    【解决方案1】:

    我的同事回答了这个问题:

    我必须将我的 response.data 转换为字符串。 (你可能想知道 - 为什么无用的函数 - 只是为了重新定义默认行为,它使用 JSON.parse 将字符串解析为对象 - 这里我们跳过这一步)

    axios.get(url, { transformResponse: [data  => data] });
    

    然后用json-bigint解析

    JSONBigInt.parse(res.data);
    

    【讨论】:

    • 另外,根据您的问题,您可能需要这样的 JSONbig:const JSONbig = require('json-bigint')({'storeAsString': true})
    【解决方案2】:

    运行这个来安装 json-bigint:npm install json-bigint --save

    然后,使用 transformResponse 作为 axios 获取请求的选项

    const jsonBig = require('json-bigint');
    
    let url = 'https://your-api';
    axios.get(url, { transformResponse: function(response) {
          return jsonBig().parse(response.data);
    }});
    

    您也可以通过以下方式使用它:

    const jsonBig = require('json-bigint');
    
    axios({
      url: 'https://your-api',
      method: 'get',
      transformResponse: function(response) {
        return jsonBig().parse(response);
      },
    })
    

    【讨论】:

      【解决方案3】:

      除了上面的答案,如何将 JSONbigint 与 axios 请求和响应拦截器集成。

      import JSONbigint from 'json-bigint'
      ...
      
      // request interceptor, preventing the response the default behaviour of parsing the response with JSON.parse
      axios.interceptors.request.use((request) => {
        request.transformResponse = [data => data]
        return request
      })
      
      // response interceptor parsing the response data with JSONbigint, and returning the response
      axios.interceptors.response.use((response) => {
        response.data = JSONbigint.parse(response.data)
        return response
      }
      
      

      范围内的整数将保留number 类型,超出范围的整数将保留BigNumber 类型。如果需要,只需在 BigNumber 类型的键上调用 toString() 即可额外将 BigNumber 解析为 string

      【讨论】:

        猜你喜欢
        • 2022-08-17
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-08
        • 2019-02-20
        • 2013-05-30
        相关资源
        最近更新 更多