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.
By default, the axios HTTP library throws an error anytime the destination server responds with a 4XX / 5XX error (for example, a 400 Bad Request ). Since axios raises an error, your workflow will stop at this step.
JSON is just a simple JavaScript object where the properties and values are wrapped around double-quotes.
You should be able to access like this:
catch (err) {
console.error(err.response.data.errors);
}
Try:
error.message
Or depending on the backend config:
error.response
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With