Search code examples
node.jsreactjsexpresssuperagent

getting bad request instead of full error message


I am trying to do error handling for POST with the same user email with the following(using superagent):

export function signUpUser(userData) {
  return async dispatch => {
    try {
      const currentUser = await request.post(`${url}/signup`).send(userData);
      set(window.localStorage, 'x-auth', currentUser);
      dispatch(signUpSuccessObject(userData));
    } catch (error) {
      dispatch(signUpFailObject(error));
    }
  };
}

I want to get the following which I can see in my network tab:

{"name":"SequelizeUniqueConstraintError","errors":[{"message":"email must be unique","type":"unique violation","path":"email","value":"[email protected]","origin":"DB","instance":

But instead all I get is:

Bad Request

My controller for API:

User.create(
      Object.assign(req.body, {
        password: bcrypt.hashSync(req.body.password, 10),
      })
    )
      .then(() => {
        const myToken = jwt.sign({email: req.body.email}, 'leogoesger');
        res.status(200).send(myToken);
      })
      .catch(err => res.status(400).send(err));
  },

Solution

  • res.send() will send plain text/html responses.

    Use res.json(myToken) and res.status(400).json(err) for a JSON API.