Javascript Node.js Passport不调用下一个函数
我正在使用节点构建一个应用程序,该节点使用Passport.js处理使用本地数据库的用户登录 因此,我有以下代码,当用户转到/profile时将调用这些代码。成功登录后,用户将被重定向到/profile。根据摩根的说法,这确实发生了Javascript Node.js Passport不调用下一个函数,javascript,node.js,passport.js,Javascript,Node.js,Passport.js,我正在使用节点构建一个应用程序,该节点使用Passport.js处理使用本地数据库的用户登录 因此,我有以下代码,当用户转到/profile时将调用这些代码。成功登录后,用户将被重定向到/profile。根据摩根的说法,这确实发生了 app.get('/profile', passport.authenticate('local-login', { session : false, failureRedirect : '/login' }), function(req, res) { c
app.get('/profile', passport.authenticate('local-login', { session : false, failureRedirect : '/login' }), function(req, res) {
console.log("testnow");
res.render('profile.ejs', {
user : req.user // get the user out of session and pass to template
});
});
我的本地登录代码如下
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
// all is well, return successful user
console.log("testdone");
return done(null, user);
});
}));
测试代码时,我登录并在瞬间重定向到配置文件。控制台打印本地登录代码中的“testdone”,但不会像预期的那样打印“testnow”。这意味着my/profile get方法中的第二个函数似乎永远不会被调用,即使本地登录正在调用下一个函数
因此,从最终用户的角度来看,您可以登录(在后台,您会被重定向到/profile以进行拆分部分),而/profile会将您重定向回/login
有没有办法解决这个问题,从而调用my/profile get方法中的第二个函数
非常感谢。我也很乐意提供任何其他信息来帮助解决这个问题。
passport.authenticate()
用于处理实际的身份验证;换句话说,获取登录凭据并将其传递给策略。如果请求已经通过身份验证,那么它并不意味着传递请求,而这正是您试图使用它的目的
相反,您希望使用类似的方法来保护用户必须登录的路由
另请参见。尝试在pasport的options对象中添加一个属性。验证此属性:
successRedirect:“/profile”
并在成功的情况下创建路由/配置文件,我不知道passport是否在您忽略身份验证后调用下一个函数successRedirect@FernandoZamperin添加成功重定向/配置文件将导致无限循环,对吗?对不起,我误解了!!!尝试成功重定向到另一个路由仅用于测试目的,以查看问题是否在于passport未呼叫next@FernandoZamperin是的,那没用。仍在重定向到/登录。将其更改为“app.get('/profile',passport.authenticate('local-login',{session:false,successRedirect:'/',failureRedirect:'/login'}),function(req,res){”,并且仍然重定向到/login而不是/@FernandoZamperin no,但是如果session设置为false,passport将永远不会知道用户已成功登录:)好的,很酷。所以我不得不改变我的方向。非常感谢。