Home > Net >  Auth Error Cannot set headers after they are sent to the client
Auth Error Cannot set headers after they are sent to the client

Time:01-05

i'm trying to handle authentication errors on my website, but when i submit wrong data i get

node:internal/errors:478 ErrorCaptureStackTrace(err); ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

and my server app is down

my code is:

router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ username: req.body.username });
    !user && res.status(400).json("Wrong data");

    const validated = await bcrypt.compare(req.body.password, user.password);
    !validated && res.status(400).json("Wrong data");

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

how can i fix it?

CodePudding user response:

This error means server is trying to send the response again to client after sending once.

If you see on errors you do res.status(400).json("Wrong data");, but you do not return and hence the code continues. Next, it hits res.status(400).json("Wrong data"); Or res.status(200).json(others); the server is again trying to send a response to client but since the response has already been sent, you get this error.

Fix is to add a return with res.status.

router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ username: req.body.username });
    if(!user) return res.status(400).json("Wrong data");

    const validated = await bcrypt.compare(req.body.password, user.password);
    if(!validated) return res.status(400).json("Wrong data");

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