leogoesger
leogoesger

Reputation: 3840

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

Upvotes: 1

Views: 2751

Answers (2)

leogoesger
leogoesger

Reputation: 3840

https://github.com/visionmedia/superagent/issues/1074

^^ Used this as a reference.

Basically, I need error.response. This will give me the entire object, which will allow me to get access to the error message.

So full working code would be:

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

Upvotes: 2

Matt
Matt

Reputation: 74791

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

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

Upvotes: 1

Related Questions