1

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.

1
  • What do you get when you console.log(err) on the response in the catch? Commented Sep 6, 2019 at 12:48

2 Answers 2

2

// 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);
  }
})

Sign up to request clarification or add additional context in comments.

Comments

0

I agree with Mohammed, you can find error message under data property.

console.log(error.response.data.message);

Comments

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.