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:05-20

I get this error whenever I use the api and send post, Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

enter image description here

This is the code !

//LOGIN
router.post("/login", async (req, res) => {
    try {
      const user = await User.findOne({ username: req.body.username });
      !user && res.status(400).json("Wrong credentials!");
  
      const validated = await bcrypt.compare(req.body.password, user.password);
      !validated && res.status(400).json("Wrong credentials!");
  
      const { password, ...others } = user._doc;
      res.status(200).json(others);
    } catch (err) {
      res.status(500).json(err);
    }
  });



module.exports = router;

I don't know why I get this error, what should I do?

CodePudding user response:

See if this works:

router.post("/login", async (req, res) => {
    try {
      const user = await User.findOne({ username: req.body.username });
      if(!user) return res.status(400).json("Wrong credentials!");
  
      const validated = await bcrypt.compare(req.body.password, user.password);
      if(!validated) return res.status(400).json("Wrong credentials!");
  
      const { password, ...others } = user._doc;
      return res.status(200).json(others);
    } catch (err) {
      return res.status(500).json(err);
    }
  });



module.exports = router;

Added returns, so that once a res.json() completes, it ensures the next one doesn't run.

  • Related