【问题标题】:Passportjs Callback, understanding arguments [duplicate]Passportjs回调,理解参数[重复]
【发布时间】:2017-02-04 07:51:40
【问题描述】:

我无法理解 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 作为参数传递。 jsfiddle.net/ccestd3o

标签: javascript node.js express passport.js


【解决方案1】:

passport.authenticate() 是一个middleware。简而言之,中间件是一个修改请求然后将其传递给下一个请求处理程序的函数。 express 中的请求处理程序是以(req, res, next) 作为参数的函数。那么passport.authenticate 是一个返回中间件 的函数,它接受(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构造函数中。

【讨论】:

  • 哦,有道理。通常,当用作中间件时,它会使用 req、res、next 参数调用。由于在这种情况下我们没有将其用作普通中间件,因此我们必须自己传递这些值。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-06-24
    • 2017-08-06
    • 2015-06-14
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2013-11-04
    • 1970-01-01
    相关资源
    最近更新 更多