JS Axios - how to get response body in event of error?

我怕爱的太早我们不能终老 提交于 2019-12-02 11:06:32

I tested it with Mocky and the error message is indeed returned in 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);
});

The code above prints Ooops, bad request!, as returned.

EDIT: apparently the problem you described can happen for a variety of reasons. See this issue.

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);
});

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

Thanks for your help everyone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!