Home > Software design >  Passing errors back in node express (UnhandledPromiseRejectionWarning)
Passing errors back in node express (UnhandledPromiseRejectionWarning)

Time:02-17

I have a login function in node:

/**
 * Logs in a user.
 */
router.post('/login', (req, res, next) => {

    let fetchedUser;

    User.findOne({ email: req.body.email }).then((user) => {
        // user not found...
        if(!user) {
            res.status(401).json({
                message: 'Auth Failed  - No matching email found...'
            })
        } else {
            // store user data;
            fetchedUser = user;
            // return a promise from brypt comparing the password and the stored password...
            return bcrypt.compare(req.body.password, user.password);
        }
    }).then((result) => {
        // if the passwords no not match throw and error
        if(!result) {
            res.status(401).json({
                error: 'Auth Failed - Passwords dont match...'
            })
        } else {
            // password is valid...
            const token = generateToken(fetchedUser.email, fetchedUser._id, req.body.remainLoggedIn );

            console.log('User logged in: '   req.body.email);

            res.status(200).json({
                _id: fetchedUser._id,
                token: token,
                name: fetchedUser.username,
                email: fetchedUser.email,
                joinDate: fetchedUser.joindate
            })
        }

    }).catch((error) => {
        res.status(401).json({
            message: 'Auth Failed: '   error
        })
    })
})

and it logs user in, but doesnt handle errors correctly. It always sends back the same error:

POST http://localhost:3001/api/user/login 401 (Unauthorized)

I tried wrapping my code in if {} else {} chains as was suggested from another similar question.

The node error is

(node:118684) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:561:11)
    at ServerResponse.header (C:\Users\i\Documents\GitHub\i-l\node_modules\express\lib\response.js:776:10)
    at ServerResponse.send (C:\Users\i\Documents\GitHub\i-l\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\i\Documents\GitHub\i-l\node_modules\express\lib\response.js:267:15)
    at C:\Users\i\Documents\GitHub\i-l\backend\routes\user.js:95:25

Where line 95 is the final catch.

Thanks!

CodePudding user response:

HTTP follows one response per request

One or more response come up with:

Error : Cannot set headers after they are sent to the client

In your case, if user is not found you're sending 401

if(!user) {
        res.status(401).json({
            message: 'Auth Failed  - No matching email found...'
        })
    }

then in catch your are sending again

catch((error) => {
    res.status(401).json({
        message: 'Auth Failed: '   error
    })
})
  • Related