2016-09-28 25 views
1

我不明白這個例子Passport自定義回調如何工作?

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 , 下一個) ?

回答

2

你簡單的例子是有點過,可能是由於不匹配的括號,如...

如果我減少對定製回調「官方」護照例子,我得到:

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 */ 
} 
+0

非常感謝! – Lev

+0

但官方的自定義回調示例指出,在使用自定義回調時,必須手動調用'req.login'。我仍然不清楚爲什麼會出現這種情況,因爲當我測試它時,我的'req.logIn'函數中沒有代碼被執行。我很想看到一個使用本地策略和自定義回調的工作示例的樣板。 – nextgentech