我在登录发生后收到此错误。代码正常工作,但在用户返回后收到此错误。
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at ServerResponse.setHeader (node:_http_outgoing:576:11)
at ServerResponse.header (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\express\lib\response.js:771:10)
at ServerResponse.location (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\express\lib\response.js:888:15)
at ServerResponse.redirect (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\express\lib\response.js:926:18)
at allFailed (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\passport\lib\middleware\authenticate.js:139:20)
at attempt (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\passport\lib\middleware\authenticate.js:174:28)
at Strategy.strategy.fail (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\passport\lib\middleware\authenticate.js:296:9)
at verified (C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\node_modules\passport-local\lib\strategy.js:82:30)
at C:\Users\Oswald\Desktop\Folders\nodeProjects\practisefolder\nodeWebAppTutorial\src\config\passport.js:17:32
守则
const usersRepo = require('../repositories/usersRepo');
const { Strategy } = require('passport-local');
function initialize(passport) {
passport.use('local.signIn', new Strategy({
usernameField: 'username',
passwordField: 'password'
}, (username, password, done) => {
(async function ValidateUser() {
try {
const users = await usersRepo.getData({ username: username });
users.forEach((user) => {
if (user.username === username && user.password === password) {
return done(null, user)
} else {
return done(null, false, { message: "user not found" })
}
})
} catch (error) {
done(error, false)
}
}())
}))
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
}
module.exports = initialize
2条答案
按热度按时间xj3cbfub1#
问题是
.forEach
中的return
语句没有停止迭代,因为它只是从当前forEach回调返回。但这不是唯一的问题,因为每次找不到用户时都会调用done()
回调。您可能正在寻找类似下面的内容:3pmvbmvn2#
在我的情况下,我得到了如下错误
为了解决该错误,我在
res
关键字之前添加了return
这是解决错误之前的代码
下面是解决错误后的代码