Error stating: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client when trying to create a login api

Viewed 22

I have been trying to create an react application and authorisation backend API for an ecommerce project. But after updating the username, email and password to mongoDB, I am not able to login with the username and password which is already given in the database. I am using CryptoJS for password encryption. Testing the API's through Postman and getting result as “wrong credentials” when trying to login And in the console I am getting an error stating that

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

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

The Code To My Login API Is Given Below.

//LOGIN
router.post("/login", async (req, res) => {
  try {
    const user = await User.findOne({ username: req.body.username });
    !user && res.status(401).json("Wrongs Credentials")
    const hashedPassword = CryptoJS.AES.decrypt(
      user.password,
      process.env.PASS_SEC
    );
    const password = hashedPassword.toString(CryptoJS.enc.Utf8);
    password != req.body.password && res.status(401).json("Wrong credentials!");
    res.status(200).json(user)
    console.log(user)
  } catch (err) {
    res.status(500).json(err);
  }
});

module.exports = router;

1 Answers

You should use regular if statements, not just for readability but it also allows you to return after sending a response (which you can only do once, hence the error):

if (! user) {
  return res.status(401).json("Wrongs Credentials");

  // this is a shortcut for:
  //   res.status(401).json("Wrongs Credentials");
  //   return;
}
…
if (password != req.body.password) {
  return res.status(401).json("Wrong credentials!");
}
Related