【发布时间】:2022-02-16 20:52:51
【问题描述】:
我在节点中有登录功能:
/**
* 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 行是最后的捕获。
谢谢!
【问题讨论】:
-
你能告诉我错误信息,以了解更多信息,在第一个示例代码中。