JS Axios - 如何在错误事件中获取响应体?

14

我希望能够从 Axios 错误捕获中获取响应体。

我正在使用 axios v0.18.0 版本。

我的 axios 代码如下:

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错误,这是我预期的,考虑到我的输入。所以,我进入了catch块。但是,我无法检索API调用返回的错误消息。

我尝试过console.out(error.response.data),但这会返回null。

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

我错过了什么?

2个回答

23

我使用Mocky测试了它,错误信息确实在error.response.data中返回。

const axios = require('axios');

// http://www.mocky.io/v2/5c06f6be3000009600d25953 (the mock api to call, it always returns 400 with an error message)

let service = axios.create({
    baseURL: "http://www.mocky.io",
    responseType: "json"
});

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

上面的代码打印出返回的Ooops, bad request!

编辑:显然,您所描述的问题可能出现各种原因。请参见问题。


谢谢留言。我运行了你的代码,但没有看到返回“糟糕的请求!”; 我得到“null”。我还阅读了你提到的链接。jacurtis(https://github.com/axios/axios/issues/960#issuecomment-398269712)发表了评论,需要查看error.response.data或error.response.data.data,但这两者都是非空的。 - Cog
奇怪...我做了一个Codepen,同样的问题出现了。但是如果我在本地用Node运行它就可以工作。 - brunobastosg
更正我之前的评论...我的意思是说error.response.data和error.response.data.data都是null。因此似乎没有直接获取错误响应的方法。 - Cog
Axios会自动读取400的响应体,但不会读取500的响应体,我正在寻找一种配置的方法... - Glass Cannon

3
这是我解决问题的方法。
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"。
谢谢大家的帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接