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

COS*_*LIM 9 javascript axios

我无法在500 errorwith axios 中获取响应文本。

在开发工具的网络选项卡中,我可以找到这样的错误消息

{"Message":"500 error message 0","Code":0,"Type":"error"}
Run Code Online (Sandbox Code Playgroud)

我用

axios()
.then(function(done) {
   //fine and can get done.data
})
.catch(function(error) {
    console.log(error.message);
}); 
Run Code Online (Sandbox Code Playgroud)

但我只能得到

Request failed with status code 500
Run Code Online (Sandbox Code Playgroud)

那么如何使用 axios 获取响应文本

Eug*_*oub 14

根据axios 自述文件

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);
  });
Run Code Online (Sandbox Code Playgroud)

  • 我使用 `console.log(error.message)` ,只得到 `Request failed with status code 500` 而不是 `error` 中的真实消息。 (2认同)
  • 是的,正如您从上面的文档中看到的,您要查找的内容应该在 `error.response.data` 中,而不是在 `error.message` 中。 (2认同)