使用 axios post 捕获错误正文 [英] catching error body using axios post
本文介绍了使用 axios post 捕获错误正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从我的后端代码发送一个状态代码 422,其中包含对错误的描述.我正在使用 axios post 发布请求,如下所示:
I am sending a status code 422 from my backend code with response body which contains the description of the error. I am using axios post as below to post a request:
post: function(url, reqBody) {
const request = axios({
baseURL: config.apiUrl,
url: url,
headers: {
'Content-Type': 'application/json',
'Authorization': sessionStorage.getItem('token')
},
method: 'POST',
data: reqBody,
responseType: 'json'
});
return request
.then((res) => {
return res;
})
.catch((error) => {
console.log(error);
return error;
})
}
问题是当后端返回错误代码 422 时,我捕获的错误对象没有关于响应正文的信息.有什么办法可以检索错误文本吗?
The problem is when backend is returning error code 422, the error object I am catching has no information about response body. Is there any way I can retrieve the error text?
推荐答案
我遇到了同样的问题,答案(按照 Axios >= 0.13)是专门检查 error.response.data
:
I had this same issue and the answer (as per Axios >= 0.13) is to specifically check error.response.data
:
axios({
...
}).then((response) => {
....
}).catch((error) => {
if( error.response ){
console.log(error.response.data); // => the response payload
}
});
请参阅此处了解更多详情.
这篇关于使用 axios post 捕获错误正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文