Home > Net >  Login process are crashed the app if I put wrong password or email with error: Cannot set headers af
Login process are crashed the app if I put wrong password or email with error: Cannot set headers af

Time:10-27

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

CodePudding user response:

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.

  • Related