最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - axios - how to deal with big integers - Stack Overflow

programmeradmin4浏览0评论

Here is my request:

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

The output is { value: 156144277082605255 }

But should be { value: 156144277082605250 }

How to deal with Big Integers in this case? I tried to use json-bigint But since I am getting response.data from axios as object - it doesn't help.

Here is my request:

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

The output is { value: 156144277082605255 }

But should be { value: 156144277082605250 }

How to deal with Big Integers in this case? I tried to use json-bigint But since I am getting response.data from axios as object - it doesn't help.

Share Improve this question asked May 4, 2017 at 15:57 kurumkankurumkan 2,7254 gold badges35 silver badges56 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

My colleague answered the question:

I had to transform my response.data into string. (you may wonder - why the useless function - just to redefine default behavior, which parses string into object with JSON.parse - in here we skip this step)

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

and then parse with json-bigint

JSONBigInt.parse(res.data);

Adding to the above answers, how to integrate JSONbigint with axios request and response interceptors.

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
}

Integers that are within the range will remain of type number and those exceeding the range will be of type BigNumber. One could additionally parse BigNumber to string if required by simply calling toString() on the keys of type BigNumber

Run this to install json-bigint: npm install json-bigint --save

Then, use the transformResponse as an option of the axios get request

const jsonBig = require('json-bigint');

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

You can also use this in the following way:

const jsonBig = require('json-bigint');

axios({
  url: 'https://your-api',
  method: 'get',
  transformResponse: function(response) {
    return jsonBig().parse(response);
  },
})
发布评论

评论列表(0)

  1. 暂无评论