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?
I tested it with Mocky and the error message is indeed returned in
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.
The main modification was to change "responseType" to "application/json".
Thanks for your help everyone.