Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch return json from POST with Axios when error 400 (Bad Request) occurs

I am making an http request in an api using React Native with Axios, I can get json and parsear it when the callback is 200, however, for example, when I call a method, for example, to register the user and step an email from a user who is already registered, he returns me an error 400 (Bad Request) but he also brings a json with the error message ("user already registered"). I need to get this error message since it is variable in the API and show to the user, but when I try to give it a console.log I get the following error:

enter image description here

json's return is this:

enter image description here

and my call code looks like this:

enter image description here

How to get this json even with return 400 in catch?

Thank you.

like image 954
Anderson Nunes Avatar asked Jul 25 '19 11:07

Anderson Nunes


1 Answers

inside of your catch Block, the error object also provides you with a response body

//... your request here
.catch(error => {
  console.log('response: ', error.response.data);
});

console.log(error) is calling the toString method of the error object which doesn't show you the response body.

error.response.data should give you the right content. Take a look at this part of the axios docs

like image 77
Bruno Paulino Avatar answered Nov 16 '22 00:11

Bruno Paulino