Javascript Passport Strategy 中的“done”回调函数是什么配置“use”函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32153865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:41:10  来源:igfitidea点击:

What is "done" callback function in Passport Strategy Configure "use" function

javascriptnode.jsexpresscallbackpassport.js

提问by Steve.NayLinAung

I'm an node.js and express.js noob. This question may seems silly but I'm really in confusion.

我是一个 node.js 和 express.js 菜鸟。这个问题可能看起来很愚蠢,但我真的很困惑。

I'm trying to configure Local Strategryauthentication by using passport. As shown in the official documentation, we can figure this Local Strategy by the following code,

我正在尝试使用Passport配置本地策略身份验证。如官方文档所示,我们可以通过以下代码来计算这个Local Strategy,

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

My confusion is about the donecallback function. When the official docs show this local strategy using as a middleware in the route handler, there is no need to pass the function parameter for this donecallback.

我的困惑是关于done回调函数。当官方文档显示此本地策略用作路由处理程序中的中间件时,无需为此done回调传递函数参数。

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

So, isn't this donecallback function will be null if we don't provide the function parameter? If not, what is that donecallback function and what processes will be happening in this donecallback function?

那么,done如果我们不提供函数参数,这个回调函数不是会为空吗?如果不是,那个done回调函数是什么,这个done回调函数中会发生什么过程?

回答by Roy Miloh

doneis a method called internally by the strategy implementation.

done由策略实现内部调用的方法。

Then it navigates you, as you can see, to one of the success/ error/ failmethods (again, by the implementation. there are more options). Each of these options may callsto the next, where in your snippet code is the following:

然后您导航,你可以看到,到的一个success/ error/fail方法(同样,通过实施。有更多的选择)。每个选项可以调用next,在你的代码片段,其中如下:

function(req, res) {
  res.redirect('/');
});

When successis called, it can attach the user to the requestor do other things, depending on your needs (it looks for the optionsyou pass to passport.authenticate). If you want to determine when nextwill be called, you should use custom callbackwhich gives you more flexibility.

success被调用时,它可以将用户附加到请求或做其他事情,这取决于您的需要(它会查找options您传递给的passport.authenticate)。如果你想确定什么时候next被调用,你应该使用custom callbackwhich 给你更多的灵活性。

I strongly recommend that you read the source.

我强烈建议您阅读源代码。