在单独的函数中调用passport.authenticate不起作用

我对Node和Passport比较陌生,我正在使用OAuth尝试login表单。 我在设置护照方面没有问题,而且function完整。

当我开始清理代码以将路由与中间件分开时,它只会失效。

在更改前后,我已经包含了部分代码。

所以,这工作:

module.exports = function(app, passport) { app.get('/login', loginIndex) app.post('/login', passport.authenticate('local-login', { successRedirect : '/profile', failureRedirect : '/login', failureFlash : true })) function loginIndex(req, res) { res.render('login.ejs', {message: req.flash('loginMessage')}) } } 

但是这不是:

 module.exports = function(app, passport) { app.get('/login', loginIndex) app.post('/login', loginAuth) function loginIndex(req, res) { res.render('login.ejs', {message: req.flash('loginMessage')}); } function loginAuth(){ passport.authenticate('local-login', { successRedirect : '/profile', failureRedirect : '/login', failureFlash : true }) } } 

所以,两者之间的唯一区别是我已经将passport.authenticate()调用移入了函数loginAuth()。 我想这与passport.authenticate()的内部工作有关,但我不确定。

谢谢。

尝试这个:

  app.post('/login', loginAuth()) 

 function loginAuth(){ return passport.authenticate('local-login', { successRedirect : '/profile', failureRedirect : '/login', failureFlash : true }) } 

在您的原始代码中,您正在执行passport.authenticate而在第二个版本中,您只是传递一个函数而不执行通行证逻辑。