在 passport.authenticate() 内部重定向时出现问题

Problem redirecting inside of passport.authenticate()

我在使用护照 js 身份验证时遇到问题。在我的 passport.authenticate() 回调中调用 res.redirect('/') 时尝试访问未定义的 属性 时出现错误。我的认证策略是这样的:

passport.use(new LocalStrategy({
  session: false
}, (username, password, done) => {
  console.log('strategy invoked');
  let user = new User('jason', 'password');
  return done(null, user);
}));

和我的路线处理程序:

app.post('/auth', 
passport.authenticate('local', { failureRedirect: '/fail'},
function(req, res){
    console.log('authenticate callback');
    console.log(req.body);   //logs undefined
    res.redirect('/');       //throws error here
  }
));

所以当我使用 curl 对 /auth 路由创建 POST 时,我收到一条错误消息:Cannot read property 'redirect' of undefined。我已经尝试了路由处理程序的多种变体,包括我只是将 successRedirect 设置为“/”但从未触发我的“/”路由处理程序的变体。我也试过这个:

app.post('/auth', (req, res) => {
passport.authenticate('local', (req, res) => {
    console.log('authenticate callback');
    console.log(req.body);
    res.redirect('/');
  })(req, res);
});

所以我的问题是:

  1. 如何访问身份验证回调中的 req 和 res 对象以便 读取请求正文并发送响应,对于 example res.redirect('/');?

  2. 如果设置 successRedirect: '/' 是更好的选择,我如何确保我的重定向 真的被关注了?

您的代码中存在错误。您将护照中间件和回调函数组合到同一个参数中。尝试下面的代码或查看文档中的示例:http://www.passportjs.org/docs/downloads/html/

app.post('/auth', passport.authenticate('local', { failureRedirect: '/fail'}), function(req, res){
    console.log('authenticate callback');
    console.log(req.body);   //logs undefined
    res.redirect('/');       //throws error here
});