我是node.js和express.js的菜鸟。这个问题可能看起来很傻,但我真的很困惑。
我正在尝试使用passport配置Local Strategry身份验证。如官方文档所示,我们可以通过以下代码来表示这个本地策略。
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回调函数不是将为空吗?如果不是,done回调函数是什么?在这个done回调函数中将发生什么过程?
发布于 2015-08-22 17:58:04
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,它为您提供了更大的灵活性。
我强烈建议您阅读源代码。
https://stackoverflow.com/questions/32153865
复制相似问题