0

I'm working on building an node/express backend and continue to receive the following error: (node:35061) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. I'm not exactly sure what i am doing wrong here... Can someone educate me on what the issue might be? TIA!

Route

userRoutes.post('', async (req, res) => {
  try {
    const { email, password } = req.body;

    const validate = await signUp.validate({ email, password });
    res.send(validate);

    const newUser = new User({ email, password });
    const sessionUser = sessionizeUser(newUser);
    await newUser.save();

    req.session.user = sessionUser;
    res.send(sessionUser);
    return;
  } catch (error) {
    res.status(400).send(parseError(error));
  }
});
Nick
  • 1,471
  • 2
  • 21
  • 35

1 Answers1

0

The problem lies here in try block

try {
    const { email, password } = req.body;

    const validate = await signUp.validate({ email, password });
    res.send(validate); //over here

    const newUser = new User({ email, password });
    const sessionUser = sessionizeUser(newUser);
    await newUser.save();

    req.session.user = sessionUser;
    res.send(sessionUser); //over here 
    return;
  }

this means is that for a given client request the server previously sent a response (either a success response with the resource requested or error response for a bad request) back to the client and now is unexpectedly trying to send another response

Solution

The simple fix for this error is to add javascript return statement to the response being sent from the if conditional to ensure that the request handler function exits(terminate) excuting code with the function once a response has being sent to the client.

The description for the return statement on MDN states

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller.

Jatin Mehrotra
  • 9,286
  • 4
  • 28
  • 67