Home > Blockchain >  Can't set headers after they are sent to the client Node.js ERROR
Can't set headers after they are sent to the client Node.js ERROR

Time:09-09

Here is my code:

  try {
    const user = await User.findOne({ email: req.body.email });
    !user && res.status(404).json("user not found");

    const validPassword = await bcrypt.compare(req.body.password, user.password)
    !validPassword && res.status(400).json("wrong password")

    res.status(200).json(user)
  } catch (err) {
    res.status(500).json(err)
  }
});

If I use the right credentials there is no problem but if I type in wrong password or email I get an error stating:

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

and the app crashes, im following a YouTube tutorial by Lama Dev on Node.js Social media API and have the code copied one by one.

CodePudding user response:

You can only send one response for a request.

Here is an example of what you are actually trying to do:

 try {
    const user = await User.findOne({ email: req.body.email });
    if (!user) {
       return res.status(404).json("user not found");
    } 

    const validPassword = await bcrypt.compare(req.body.password, user.password)
    if(!validPassword) {
       return res.status(400).json("wrong password")
    }
    res.status(200).json(user)
  } catch (err) {
    res.status(500).json(err)
  }
});

Note that the response is returned, which allows exits the function when a response should be sent. You are checking to see IF a user does not exists, and IF they have an invalid password.

  • Related