我在節點中有一個登錄功能:
/**
* 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 行是最后的捕獲。
謝謝!
uj5u.com熱心網友回復:
HTTP 遵循每個請求的一個回應
One or more response come up with:
錯誤:在將標頭發送到客戶端后無法設定標頭
在您的情況下,如果找不到用戶,您將發送 401
if(!user) {
res.status(401).json({
message: 'Auth Failed - No matching email found...'
})
}
然后在趕上你再次發送
catch((error) => {
res.status(401).json({
message: 'Auth Failed: ' error
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/428893.html
