在axios中,如何抓取network选项卡报错的response error body?

In Axios, how do I capture the response error body that the network tab reports?

我正在使用 axios 0.21.1。当我发出 POST 请求时,出现 400 错误,我可以在我的开发工具 -> 网络选项卡的“响应”选项卡中看到此响应,

{"data":[" value does not allow numbers"]}

如何在变量中捕获该错误?我试过这个

  axios.post(`/api/myendpoint`,
    { 
      data: 2
    },
    {
      headers: {'ACCEPT': 'application/json'}
    })
    .then(response => {
      …
    })
    .catch(response => {
      console.log(response.data);

但是“response.data”打印出“undefined”。我也尝试过“response.body”,但也未定义。

你应该像这样捕获错误和 return 正文:

.catch(error) => {
  console.log(error.response.data);
}

详情在Axios document

捕获错误,检查状态并根据需要使用它

 axios.post(`/api/myendpoint`,
{ 
  data: 2
},
{
  headers: {'ACCEPT': 'application/json'}
},
.then(response => {
  …
})
.catch((error) => {
   if (error.response && error.response.status === 400)  {
      let errorVar = error.response.data;
      console.log(errorVar);
   }
});