Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 257
H. Doe Avatar asked May 22 '17 22:05

H. Doe


People also ask

How do you fix there was a problem with the server 400?

Clear YouTube App Data & Cache To do the same, head to Settings > Apps > All Applications and select 'YouTube. ' Then, click on 'Storage' and tap 'Clear Data. ' This will reset your YouTube app to default and will likely fix the server error 400.

How do you handle 400 error in API?

A 400 status code means that the server could not process an API request due to invalid syntax. A few possibilities why this might happen are: A typo or mistake while building out the request manually, such as mistyping the API endpoint, a header name or value, or a query parameter.


Video Answer


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
        });
like image 156
Mo D Genesis Avatar answered Sep 28 '22 05:09

Mo D Genesis


Just looking at the axios documentation, it looks like the response should be exposed in the error object (i.e. console.log(error.response)).

More information about different info provided when the response code falls out of 2xx here: https://github.com/mzabriskie/axios#handling-errors

like image 20
Lance Whatley Avatar answered Sep 28 '22 06:09

Lance Whatley