skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
    • The keyword return prevents the execution of your code. That means that any lines of code after it will not be executed.
    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);
        }
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search