在 node express 中传回错误 (UnhandledPromiseRejectionWarning)

Passing errors back in node express (UnhandledPromiseRejectionWarning)

我在节点中有登录功能:

/**
 * 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
        })
    })
})

它让用户登录,但没有正确处理错误。它总是发回相同的错误:

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

我尝试按照另一个类似问题的建议将我的代码包装在 if {} else {} 链中。

节点错误为

(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

第 95 行是最后一个捕获点。

谢谢!

HTTP 遵循每个请求的一个响应

One or more response come up with:

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

在您的情况下,如果找不到用户,您将发送 401

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

然后在赶上你再次发送

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