我希望能够从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错误。因此,我遇到了麻烦。但是,我无法检索API调用返回的错误消息。

我尝试做一个console.out(error.response.data),但这返回null。

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

我想念什么?

最佳答案

我使用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!,作为返回。

编辑:显然,您所描述的问题可能由于多种原因而发生。请参阅this问题。

关于javascript - JS Axios-发生错误时如何获取响应正文?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53620625/

10-11 22:12
查看更多