I am currently working on handling authentication errors for my website. However, when I submit incorrect data, I encounter the following error:
node:internal/errors:478 ErrorCaptureStackTrace(err); ^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
As a result, my server application is down.
This is the code I am using:
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username });
!user && res.status(400).json("Wrong data");
const validated = await bcrypt.compare(req.body.password, user.password);
!validated && res.status(400).json("Wrong data");
const { password, ...others } = user._doc;
res.status(200).json(others);
} catch (err) {
res.status(500).json(err);
}
});
Can anyone suggest how I can fix this issue?