0

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);
    }
})

DannyMac
  • 45
  • 4
  • In addition to what is shown in the "question already has answers here" link above, you also should NOT call `next()` after you've send a response. That will continue routing and will then try to send another response. So, don't call `next()` if you've already sent a response. – jfriend00 Jan 25 '23 at 19:34

0 Answers0