I have a login route function below that takes in the user input. However, I am getting the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to client.
Is there anything in my code below, that I can change to prevent this? Thanks!
router.post('/login', async (req, res, next) => {
try {
const user = await User.findOne({ username: req.body.username });
!user && res.status(401).json('wrong credentials!')
const hashedPassword = Cryptojs.AES.decrypt(
user.password,
process.env.PASS_SEC);
const Orginalpassword = hashedPassword.toString(Cryptojs.enc.Utf8);
Orginalpassword !== req.body.password &&
res.status(401).json('wrong credentials!');
const accessToken = jwt.sign({
id: user._id,
isAdmin: user.isAdmin
},
process.env.JWT_SEC,
{expiresIn:'3d'}
);
const { password, ...others} = user._doc;
res.status(200).json({...others, accessToken})
return next();
} catch (error) {
res.status(500).json(error);
}
})