Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

I am using axios v0.18.0.

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

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.

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

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.

What am I missing?

like image 520
Cog Avatar asked Dec 04 '18 20:12

Cog


People also ask

How do you catch error responses in Axios?

axios. get('/my-api-route') . then(res => { // Work with the response... }). catch(err => { // Handle error console.

Why we use Axios in node JS?

Axios is a promise based HTTP client for the browser and Node. js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.

What is ERR response?

A standardized error format is returned in the body of the response whenever there is an error while fulfilling the request. This is accompanied by the response status code, which provides additional insight.

What does Axios post return?

Once you make a request, Axios returns a promise that will resolve to either a response object or an error object.


2 Answers

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.

like image 110
brunobastosg Avatar answered Oct 02 '22 18:10

brunobastosg


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.

like image 35
Cog Avatar answered Oct 02 '22 19:10

Cog