Home > front end >  Cannot set headers after they are sent to the client (Node.js)
Cannot set headers after they are sent to the client (Node.js)

Time:11-30

So basically when I try to log a user in and I type the password or username wrong and then I try to log in with correct credentials I get this error.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (D:\ecom website\ecom backend\node_modules\express\lib\response.js:794:10)
    at ServerResponse.send (D:\ecom website\ecom backend\node_modules\express\lib\response.js:174:12)
    at ServerResponse.json (D:\ecom website\ecom backend\node_modules\express\lib\response.js:278:15)
    at D:\ecom website\ecom backend\routes\auth.js:57:21
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...

And this is my code in auth.js


//LOGIN

router.post('/login', async (req, res) => {
  try {
    const user = await User.findOne({
      username: req.body.username,
    });

    !user && res.status(401).json('Wrong User Name');

    const hashedPassword = CryptoJS.AES.decrypt(
      user.password,
      process.env.PASS_SEC
    );
    const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);

    const inputPassword = req.body.password;

    originalPassword != inputPassword && res.status(401).json('Wrong Password');

    const accessToken = jwt.sign(
      {
        id: user._id,
        isAdmin: user.isAdmin,
      },
      process.env.JWT_SEC,
      { expiresIn: '3d' }
    );

    const { password, ...others } = user._doc;
    res.status(200).json({ ...others, accessToken });
  } catch (err) {
    res.status(500).json(err);
  }
});

What should I do? Is something wrong with my code?

CodePudding user response:

!user && res.status(401).json('Wrong User Name');

as a statement is IMHO quite bad style. And as you see, it leads to errors, because your code doesn't step out of this handler after having sent the headers. It just continues with the next statment and eventually reaches another res.status(...). This will try to set some headers again, which isn't allowed. And that's what the error message is telling you.

Use

if (!user) {
  return res.status(401).json('Wrong User Name');
}

instead. This will return from handler and not execute the remaining code in your function ... Same of course for all other instances where you use this pattern.

CodePudding user response:

I see that you use the res.status(code).json(content) command multiple times in your code, but you never exit the function after sending the response. As a result, after one such command - the code will continue in the function and will try to send another response, and this is where you get the error: the server is trying to send multiple responses for one request.

  • Related