Reputation: 494
I'm building Node & React application and I'm working on authentication now. For example when someone will type e-mail that already exist in database, I would like to send a response with error with proper status and message that email already exist.
I'm already done with sending errors when it's needed. Problem is that even if I pass error message within, I can not display it on frontend.
back-end (Node):
User.find({ email: email })
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: 'Mail exists' // <-- I want to pass message here
})
}
front-end (React):
axios.post('http://localhost:3000/user/signup', newUser)
.then(response=> {
dispatch({
type: actionTypes.SIGNUP_SUCCESS
})
localStorage.setItem('JWT_TOKEN', response.data.token)
axios.defaults.headers.common['Authorization'] = response.data.token
})
.catch((err)=> {
console.log(err.message) // <-- I want to display message here
})
My actual result is that i see Request failed with status code 409
in my console.
Therefore I would like to see Mail exists
.
Thank You for help :)
Best regards.
Upvotes: 1
Views: 4140
Reputation: 19
I agree with Mohammed, you can find error message under data property.
console.log(error.response.data.message);
Upvotes: 0
Reputation: 3426
// you can try below code in your catch block
.catch((err)=> {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
if (err.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
})
Upvotes: 2