0
votes

I am making a rest api, and am aware that an incorrect username or password should return a status code of 401. The problem is I can't send an error message in the response with this status code.

Is there anything wrong with sending a status code of 200 when a user isn't found so that I can send a message to the front end:

User.findOne({ email: req.body.email }).then((user) => {
if (!user) {
res.status(200).json({ message: 'Username not found'}); 
return;
}

If I send a 400 or 401, then if I make an axios request to the route it rejects the promise and I can't receive the message. Is there any way to return a status code of 400/401 and send json back? I would greatly appreciate any help. This is my front end call to the route:

export const loginUser = ({ email, password}) => 
async (dispatch, getState) => {
    const res = await axios.post(`/api/login`, {email, password}).catch(() => { 
        dispatch({ type: 'AUTH_ERROR', payload: res.data.message })  //error here because no res
    });

     dispatch({
            type: 'USER_LOGIN',
            payload: res.data._id
        });
 }
2

2 Answers

0
votes

You can send a 400 or 401 status code and get the data at catch() doing like this:

catch(err => console.log(err.response.message))
0
votes

Actually you can send a message with a 401 message

You can try this:

User.findOne({ email: req.body.email }).then((user) => {
  if (!user) {
    res.status(401).send({ rtnCode: 1 }); 
    return;
  }
}

and to handle the response error I can suggest you to do this:

export const loginUser = ({ email, password }) =>
  async (dispatch, getState) => {
    try {
      const res = await axios.post('/api/login', {email, password})
      dispatch({ type: 'USER_LOGIN', payload: res.data._id })
    } catch (error) {
      if (error.response.status === 401) {
        if (error.response.data.rtnCode === 1) {
          console.log('Username not found!')
        }
      } else if (error.response.status === 400) {
        // Bad request
      } else {
        // Something goes really wrong
      }
    }
  }

To see if user or passport is wrong you can use rtnCode. I found this approach in this page.