Home > front end >  Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Time:12-28

Im getting this error when i try to login with wrong password.

I get "Wrong username or password!" in json body but after that my app crashes and i've to restart the server again.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:400:5)
    at ServerResponse.setHeader (node:_http_outgoing:663:11)
    at ServerResponse.header (/home/harshil/projects/mern-netflix/api/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/home/harshil/projects/mern-netflix/api/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/home/harshil/projects/mern-netflix/api/node_modules/express/lib/response.js:278:15)
    at /home/harshil/projects/mern-netflix/api/routes/auth.js:91:21
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

Node.js v19.3.0

** And my code** :

const router = require("express").Router();
const User = require("../models/User");
const CryptoJS = require("crypto-js");
const jwt = require("jsonwebtoken");

//REGISTER
router.post("/register", async (req, res) => {
  const newUser = new User({
    username: req.body.username,
    email: req.body.email,
    password: CryptoJS.AES.encrypt(
      req.body.password,
      process.env.SECRET_KEY
    ).toString(),
  });
  try {
    const user = await newUser.save();
    res.status(201).json(user);
  } catch (err) {
    res.status(500).json(err);
  }
});

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

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

    originalPassword !== req.body.password &&
      res.status(401).json("Wrong password or username!");

    const accessToken = jwt.sign(
      { id: user._id, isAdmin: user.isAdmin },
      process.env.SECRET_KEY,
      { expiresIn: "5d" }
    );

    const { password, ...info } = user._doc;

    res.status(200).json({ ...info, accessToken });
  } catch (err) {
    res.status(500).json(err);
  }
});

module.exports = router;

i hope someone can help me solve this err. thanks.

i want that it doesnt crash when login with wrong user or password.

CodePudding user response:

!user && res.status(401).json("Wrong password or username!"); does not stop the execution of your function. And therefore, after sending a response to the client, further responses (here: your password check) are possibly sent - which yield the error you posted. It should be:

if (!user) {
  return res.status(401).json("Wrong password or username!");
}

Same for originalPassword !== req.body.password && res.status(401).json("Wrong password or username!");

  • Related