Home > OS >  Express server is crashing once the wrong credential is sent
Express server is crashing once the wrong credential is sent

Time:10-17

I am trying to log in using email and password but if I log in using the right data, it is fine. If I enter any one of the fields wrong then it shows the expected output and crashes instantly and I have to restart the server from npm start. No further API calls can be made afterward if I do not restart the server.

usersRoute:

// Login

    router.post('/login', async (req, res) => {
        try {
            const user = await User.findOne({
                email: req.body.email,
            });
            !user && res.status(401).json('email does not exist in the DB');
    
            const bytes = CryptoJS.AES.decrypt(
                user.password,
                process.env.SECRET_KEY
            );
            const originalPassword = bytes.toString(CryptoJS.enc.Utf8);
    
            originalPassword !== req.body.password &&
                res.status(401).json('wrong password');
    
            const accessToken = jwt.sign(
                {
                    id: user._id,
                },
                process.env.SECRET_KEY,
                { expiresIn: '300000' }
            );
    
            const { password, ...info } = user._doc;
    
            res.status(200).json({ ...info, accessToken });
        } catch (err) {
            res.status(500).json(err);
        }
    });

CodePudding user response:

Add a return statement to your res.send calls when you intend to exit the function early. Otherwise, the rest of your code continues to execute and throws an error because the response is already sent.

Your code is likely throwing an error, because your response is being sent multiple times. Then, your catch is trying to send another response, which throws yet another error.

CodePudding user response:

When you enter a bad credentials, the execution continues to the lines after

!user && res.status(401).json('email does not exist in the DB');

to stop execution of the handler, change this line to:

if(!user) { res.status(401).json('email does not exist in the DB'); return;}
  • Related