4

I'm using passportjs for user authentication, and in the event that authentication is unsuccessful, I'd like to display a custom error message that is rendered on client side (in this case, React/Redux).

Route:

app.post(
    '/api/login',
    (req, res) => {
      passport.authenticate('local-login', (err, user, info) => {

        if (!user) return res.status(400).send({ msg: 'Please verify account first' });

      })(req, res);
    }
  );

Action creator:

export const loginUser = (values, history) => async dispatch => {
  try {
    const res = await axios.post('/api/login', values);
    dispatch(deleteMessage());
    dispatch({ type: FETCH_USER, payload: res.data });
    history.push('/');
    window.Materialize.toast(`Welcome back ${res.data.local.email}!`, 4000);
  }
  catch(err) {
    console.log('Error:', err);
  }
}

When I catch the error and console log it out however, I get a standard status 400 error message instead of: { msg: 'Please verify account first' }

Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

Is there a better way to display custom error messages?

3 Answers 3

14

Modify from console.log(error) to console.log(error.response) in catch.

ref : https://github.com/axios/axios/issues/960#issuecomment-309287911

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

1 Comment

Works a charm! Thanks
0

You have to be in the scope of variable res, I would suggest the following approach (outside .catch()):

if(res.status === 400) {
  const error_msg = res.msg
  dispatch(loginError(error_msg))
}

Comments

0
console.log('Error:', err);

You could change this too whatever error message you want. Or do you want the response err from the server to be { msg: 'Please verify account first' }

1 Comment

Yes I want the response err from the server to be { msg: 'Please verify account first' }

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.