Login process are crashed the app if I put wrong password or email with error: Cannot set headers after they are sent to the client

Issue

I have a problem with my backend. I don’t know why the app is crushes. I’m not sending headers twice here. May be you know how to fix that? If I’m entering wrong password or username everithing is break. But if not wrong data —> everything is fine..

// Authentication
router.post("/login", async (req, res) => {
    try{

        const user = await User.findOne({username: req.body.username});
        !user && res.status(401).json("User not found.");

        const hashedPassword = CryptoJs.AES.decrypt(user.password, process.env.SECRET);
        const originalPassword = hashedPassword.toString(CryptoJs.enc.Utf8);

        originalPassword !== req.body.password && 
            res.status(401).json(`Incorrect username or password`);

            const token = jwt.sign({
                id: user.id,
                isAdmin: user.isAdmin,
            }, process.env.JWT_SECRET, { expiresIn: "3d" });

        const {password, ...otherParams} = user._doc;

        res.status(200).json({...otherParams, token});

    } catch(e) {
        res.status(500).json("ERROR ERROR ERROR " + e);
    }
})

Solution

You should use return to stop execution after sent response (return res.status()). One by one all res.status are executing. Only one response should be sent.

Answered By – Ethan Hunt

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published