【问题标题】:How does the Passport custom callback work?Passport 自定义回调如何工作?
【发布时间】:2016-09-28 01:51:42
【问题描述】:

我不明白这个例子

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

我在这里看到的是

app.get('path', function(req, res, next) {/*bunch of code*/})(req, res, next)

由于它不是对放置在 (req, res, next) 后面的函数的引用,这如何工作?

【问题讨论】:

    标签: javascript node.js express passport.js


    【解决方案1】:

    您的简化示例有点偏离,可能是由于括号不匹配等......

    如果我减少自定义回调的“官方”护照示例,我会得到:

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

    所以我的第一个假设是 (req, res, next) 被传递给从 passport.authenticate 返回的符合 express-middleware 的函数。

    如果我在the authenticate code on GitHub 附近闲逛,大约在第 81 行左右(在撰写本文时),看起来这就是开始发生的事情:

    return function authenticate(req, res, next) {
        /* lots and lots of lines follow */
    }
    

    【讨论】:

    • 但是官方自定义回调示例强调了在使用自定义回调时必须手动调用req.login。我仍然不清楚为什么会这样,因为当我测试它时,我的req.logIn 函数中没有代码被执行。我希望看到一个样板,其中包含一个使用本地策略和自定义回调的工作示例。
    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多