I'm very puzzled at the moment, as I'm utilizing bcrypt to authenticate a user login and encountering an unexpected error:
Error: Can't set headers after they are sent.
Let me share with you the code snippet for that particular route:
router.post('/login', (req, res, next) => {
User.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length < 1) {
res.status(401).json({
message: 'Auth failed'
});
}
bcrypt.compare(req.body.password, user[0].password, (err, result) => {
if (err) {
res.status(401).json({
message: 'Auth failed'
});
}
if (result) {
res.json(200).json({
message: 'Auth successful'
});
}
return res.status(401).json({
message: 'Auth failed 3'
});
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
I initially suspected that the issue might have stemmed from the if else
clauses and inadvertently setting the header twice, but I believe I'm clearing them before proceeding to the next condition. Could it be that I'm misinterpreting something here?