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
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
See if this works:
Added returns, so that once a
res.json()
completes, it ensures the next one doesn’t run.return
prevents theexecution
of your code. That means that any lines of code after it will not be executed.