【问题标题】:Passport Js documentation Custom Callback syntaxPassport Js 文档自定义回调语法
【发布时间】:2018-07-09 01:20:16
【问题描述】:

我正在为我的节点应用程序使用 passport.js。在自定义回调部分,我找到了以下代码(可以说是代码 A):

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);
});

我的问题是我无法理解最后的传递 (req, res, next)。下面的代码如何(让我们说它是代码 B):

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);
    });
  });
});

代码 B 与代码 A 有何不同?
如果我简化代码 A,那么它将是这样的:

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

进一步
passport.authenticate(..)(req, res, next);
这意味着像
这样的表达 函数(..)(req,res, next)
我的问题更多是关于理解语法
函数(..)(参数)

【问题讨论】:

    标签: javascript node.js passport.js


    【解决方案1】:

    authenticate() 函数结构如下:

    module.exports = function authenticate(passport, name, options, callback) {
      // ...
      return function authenticate(req, res, next) {
          // ...
          strategy.success = function(user, info) {
            if (callback) {
              return callback(null, user, info);
            }
          }
         // ...
      })
    };
    

    所以它需要两个系列的参数:

    • 第一个(在您的情况下为'local' 和回调函数)用于告诉护照对您进行身份验证,以及如何进行;
    • 第二个处理函数以使用reqresnext 参数控制您的应用程序。

    希望能帮助你理解!

    【讨论】:

    • 谢谢!! .是的,现在我能理解了
    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2017-10-31
    • 2019-03-18
    • 1970-01-01
    相关资源
    最近更新 更多