Meghan King
Meghan King

Reputation: 215

How to see axios error response JSON in React

I have a form in my react which allows users fill out their info and then sends a Post requests to create a new user in my database once submitted. I am using axios to make the http call with a node backend. The post request works on the backend, but I am now trying to handle errors on the front end (i.e. if a user enters an invalid email, the backend catches this and sends an error status back, and I want to display a message to the user saying they need to enter a valid email, etc).

I have the following code on my backend to handle the request:

const { check, validationResult } = require('express-validator/check');

studentRoutes.route('/add').post([
  check('email').isEmail(), check('class_year').isInt({min: 2014, max: 2022})],
  function (req, res) {

  //make sure input is valid
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }
  .
  .
  .
  //post call succesful
  res.status(200).send("Student successfully Added to database");
});

On the front end, I make the http call as follows:

app.post('student/add', obj)
    .then(res => console.log(res.data))
    .catch(err => console.log(err));

where app is axios.

When I try this with correct data (i.e. should not return error), the message "Student successfully added to database" prints to the console as expected.

When I try this with a bad email (i.e. should return error), all that is printed to my console is:

(X) POST http://localhost:4000/student/add 422 (Unprocessable Entity)
Error: Request failed with status code 422
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:78)

Where the first POST error is caught by my browser and the second part starting "Error: ..." is printed to the console.

When I try to access the error (err.errors or similar) it returns undefined. How can I access the status code and the body of the error sent?

Note: I have also tried replacing the line return res.status(422).json({ errors: errors.array() }); with return res.status(422).send({ errors: errors.array() }); but that does not help and the results are the same.

Upvotes: 7

Views: 16289

Answers (2)

Colin Ricardo
Colin Ricardo

Reputation: 17249

You should be able to access like this:

catch (err) { 
  console.error(err.response.data.errors);
}

Upvotes: 18

Shivam Gupta
Shivam Gupta

Reputation: 1238

Try:

error.message

Or depending on the backend config:

error.response

Upvotes: 8

Related Questions