2

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)

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! you're amazing, thats for also linking me to the axios docs, should've read them earlier

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.