强制axios将“数学符号”解释为字符串

时间:2020-04-16 16:17:52

标签: javascript axios

我有一个AJAX调用,它得到一些字符串,例如:

9315554e54,但事实是当它们应解释为纯字符串响应时,它们被解释为数字931555.4e+54

这是代码:

return axios.post('getPath', {id_path: id_path}).then((r) => {
   console.log(r.data); // would give something like 931555.4e+54 when it should be 9315554e54
   // tried this which would not work since it will be incremented by 1 due to the mathematic notation : (9315554e55)
   console.log(r.data.replace(/(\+|\.)/g, '')) 
  }).catch(function (error) {
     console.log(error);
  });

我能得到一个字符串吗?

1 个答案:

答案 0 :(得分:3)

axios库解析响应using JSON.parse by default。这是配置的transformResponse参数的一部分。

如果您的响应是纯字符串,则此函数将尝试将其解释为JSON。

var parsed = JSON.parse('9315554e54');
window.document.write(parsed, ' ', typeof(parsed));

然后解决方案是覆盖此默认行为:

return axios.post('getPath', {id_path: id_path}, {
  transformResponse: (data) => data,
}).then((r) => {
  console.log(r.data);
}

或更简洁

return axios.post('getPath', {id_path: id_path}, {
  transformResponse: null,
}).then((r) => {
  console.log(r.data);
}