JS Axios-发生错误时如何获取响应正文? [英] JS Axios - how to get response body in event of error?

查看:262
本文介绍了JS Axios-发生错误时如何获取响应正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够从Axios错误捕获中获取响应正文.

I want to be able to get the response body back from an Axios error catch.

我正在使用axios v0.18.0.

I am using axios v0.18.0.

我的axios代码如下:

My axios code looks like this:

let service = axios.create({
                baseURL: "https://baseUrl.azurewebsites.net",
                responseType: "json"
            });

        service.defaults.headers.common['authorization'] = `Bearer ${token}`;

        service.post("/api/method", params).then(result => {
            console.log('success',result);
        }).catch(error=>{
            console.log('error');
            console.log(error);
        });

鉴于我的输入,我的API调用返回了我期望的400错误.因此,我遇到了麻烦.但是,我无法检索API调用返回的错误消息.

My API call is returning a 400 error as I expected, given my inputs. So I am hitting the catch block. However I'm not able to retrieve the error message that's returned by the API call.

我尝试执行console.out(error.response.data),但这返回null.

I've tried doing a console.out(error.response.data), but this returns null.

我已经使用Postman验证了API调用确实在响应正文中返回了错误消息,因此API并不是问题.

I've verified using Postman that the API call does return an error message in the response body, so the API isn't the problem.

我想念什么?

推荐答案

这是我为解决此问题所做的事情.

Here is what I did to fix the problem.

let options = {
    baseURL: "http://www.mocky.io",
    responseType: "application/json"
};

//service.post("/v2/5c06f6be3000009600d25953",{}).then(result => {
axios.post("/v2/5c06f6be3000009600d25953",null,options).then(result => {
    console.log('success', result);
}).catch(error => {
    console.log(error.response);
});

主要修改是将"responseType"更改为" application/json ".

The main modification was to change "responseType" to "application/json".

感谢大家的帮助.

这篇关于JS Axios-发生错误时如何获取响应正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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