xarielah
xarielah

Reputation: 543

Getting status 400 as an error instead of json response

I have a front-end connected to back-end, using http requests. I'm experiencing this thing where if I return res.status(200) I get a response which I can send with that response a message. But when I'm sending res.status(400). I'm getting an red error on console rather than a parsable response.

app.post('/new', (req, res) => {
    const { fullname, phone, country, img } = req.body
    return res.status(200).json({
        title: 'Ok, we got you!'
    })
})

// If I'm changing that status to 400 I get that red error on console and I cannot parse from it anything (anything atleast that I want)

Upvotes: 2

Views: 7069

Answers (1)

Salvino D'sa
Salvino D'sa

Reputation: 4506

Yes, and that's the correct behaviour with HTTP requests. HTTP 400 Bad Request indicates an error rather then a successful response from your web server. So you need to catch the error thrown by the server with either a .catch() clause or a try/catch block in order to access the data returned on your client side. You're server code is absolutely fine. Just add the code below to your client side application.

Using .catch approach
axios.get('/foo')
  .catch(function(error) {
      console.log(error.response.data);
      console.log(error.response.data.title); // your title
      console.log(error.response.status);
      console.log(error.response.headers);
  });
Using try/catch approach
try {
  const resp = await axios.get('/foo');
} catch (error) {
  console.log(error.response.data);
  console.log(error.response.data.title); // your title
  console.log(error.response.status);
  console.log(error.response.headers);
}
  • For more information visit this link

Upvotes: 4

Related Questions