JS Axios-发生错误时如何获取响应正文?

Cog*_*Cog 0 javascript error-handling axios

我希望能够从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);
        });
Run Code Online (Sandbox Code Playgroud)

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

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

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

我想念什么?

bru*_*osg 9

我使用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);
});
Run Code Online (Sandbox Code Playgroud)

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

编辑:显然,您所描述的问题可能由于多种原因而发生。看到这个问题。