我是 node.js 和 express.js 菜鸟。这个问题可能看起来很傻,但我真的很困惑。
我正在尝试配置 Local Strategry使用 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);
});
}
));
我的困惑是关于 done
回调函数。当官方文档显示此本地策略在路由处理程序中用作中间件时,无需为此 done
回调传递函数参数。
app.post('/login',
passport.authenticate('local'),
function(req, res) {
res.redirect('/');
});
那么,如果我们不提供函数参数,这个done
回调函数是不是会为null?如果不是,那个done
回调函数是什么,这个done
回调函数会发生什么过程?
最佳答案
done
是一个方法 called internally by the strategy implementation .
然后,如您所见,它会将您导航到 success
/error
/fail
方法之一(同样,通过实现.there are more options)。
这些选项中的每一个都可以calls到 next
,您的代码段中的代码如下:
function(req, res) {
res.redirect('/');
});
当调用success
时,it can attach the user to the request或根据您的需要做其他事情(它会查找您传递给 passport.authenticate
的 options
)。如果您想确定何时调用 next
,您应该使用 custom callback
这为您提供了更大的灵 active 。
我强烈建议您阅读源代码。
关于javascript - Passport Strategy中的 "done"回调函数是什么配置 "use"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32153865/