使用axios post捕获错误正文 [英] catching error body using axios post

查看:1092
本文介绍了使用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 
    }
});

有关更多详细信息,请参见此处.

See here for more details.

这篇关于使用axios post捕获错误正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆