如何使用axios处理500错误消息

20

我无法使用axios获得 500错误 的响应文本。

在开发者工具的“网络”选项卡中,我可以找到以下错误信息:

{"Message":"500 error message 0","Code":0,"Type":"error"}

我使用

axios()
.then(function(done) {
   //fine and can get done.data
})
.catch(function(error) {
    console.log(error.message);
}); 
但是我只能获得。
Request failed with status code 500

那么我该如何使用 axios 获取响应文本呢?


请查看以下链接:https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253 - MorKadosh
1个回答

32
根据 axios readme 的说明:
axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

2
我使用 console.log(error.message),但只能得到 Request failed with status code 500 而无法获取 error 中的真实信息。 - COS LIM
6
如上所述的文档显示,你需要查找的内容应该在error.response.data中,而不是error.message中。 - Eugene Ghanizadeh Khoub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接