How to catch the server response, even if 400 bad request error occured?

Viewed 20990

Consider following code. It's just a simple http post request with axios library.

axios.post('http://localhost/users', this.state)
        .then(function(response) {
          if (response.status == 201) {
            browserHistory.push('/features');
          } 
        })
        .catch(function(error) {
          console.log(error);
        })

If user enters a wrong data to an input, the response from server holds info, e.g.

  • password has to be longer then...
  • mail missing the @ sign
  • etc...

but unfortunately, I don't know how to get into that response if there's a 400 bad request status. It just shows the error, but I'm unable to get the response.

If the response status is 201, it properly shows the response. But in case of 400, even if I change the condition and add else if (response.status == 400) { console.log(response) } it doesn't show up the response.

Any help highly appreciated.

2 Answers

you need to log the data of the response:

axios.post('http://localhost/users', this.state)
        .then(function(response) {
          browserHistory.push('/features');
        })
        .catch(function(error) {
          console.log(error.response.data); // this is the part you need that catches 400 request
        });
Related