Passportjs 回调,理解参数

Passportjs Callback, understanding arguments

我无法理解 Passport.js 的自定义回调发生了什么。我不明白最后的(req, res, next)。我们应该从闭包中获得这些值吗?

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next); //<=== What is the purpose of this?
});

是的,(req, res, next) 将这些值从路由器上下文传递到您的 passport.authenticate 函数中。如果我是你,我也会研究你的路由器的中间件(express?) - 这是一种向你的路由添加身份验证的简单方法,而不是你在这里进行的精细方式(必须将 passport.auth 添加到您要验证的每条路线)。

passport.authenticate() 是一个 middleware。简而言之,中间件是一种修改请求然后将其传递给下一个请求处理程序的函数。 express 中的请求处理程序是将 (req, res, next) 作为参数的函数。那么,passport.authenticate 是一个函数,它 returns 一个中间件 ,它以 (req, res, next) 作为参数。

一般会这样使用:

app.get('/login', passport.authenticate());

由此 passport.authenticate() 将修改请求,确保用户已通过身份验证,然后将其传递给下一个处理程序。

在这种情况下,我们希望passport.authenticate多做一点,所以我们替换:

app.get('/login', passport.authenticate());

相当于:

app.get('/login', function (req, res, next) {
  passport.authenticate()(req, res, next)
});

然后将更多逻辑添加到 passport.authenticate 构造函数中。