2016-06-28 23 views
0

我對javascript語法有疑問。實際上,當我自學MEAN教程(https://thinkster.io/mean-stack-tutorial#adding-authentication-via-passport)時,我想出了編碼。下面有一個非常受歡迎的編碼。執行護照nodejs時的javascript語法

})(req, res, next); 

(req,res,next)似乎是參數,但沒有函數使用該參數。也許我現在還不夠聰明,所以我看不到它。 有沒有人可以幫助我呢?謝謝。

router.post('/login', function(req, res, next){ 
if(!req.body.username || !req.body.password){ 
    return res.status(400).json({message: 'Please fill out all fields'}); 
} 

passport.authenticate('local', function(err, user, info){ 
    if(err){ return next(err); } 

    if(user){ 
    return res.json({token: user.generateJWT()}); 
    } else { 
    return res.status(401).json(info); 
    } 
})(req, res, next); 
}); 
+0

古稱IIEF或直接調用,當語句返回功能 –

+0

總之,'護照.authenticate'返回一個接受三個參數'req','res'和'next'的函數。正如@AliTorabi所說,通過將'(req,res,next)'追加到前一個函數調用中,立即調用它。 – slugonamission

+0

passport.authenticate返回該函數,就像:'var func = passport.authenticate ...();'然後'func(req,res,next)' –

回答

2

要了解發生了什麼,你應該知道什麼是「中間件」是快遞。這是,你可以通過來表達一個函數會得到一個請求對象,響應對象,以及下一個功能:

function middleware(req, res, next) { 
... 
} 

中間件,可以「點擊」進入路徑的HTTP請求將遵循通過快速申請,並執行某些操作。

您可能已經注意到,中間件函數簽名看起來很像你的示例代碼:

router.post('/login', function(req, res, next) { ... }); 

這是一個路由處理程序被調用爲POST請求/login。路由處理程序與中間件類似,因爲它們使用相同的參數進行調用,並執行某些操作(通常,next未用於路由處理程序,但仍將作爲參數傳遞)。

您可以「堆疊」中間件,太:

router.post('/login', 
    function (req, res, next) { ... }, // first middleware 
    function (req, res, next) { ... }, // second middleware 
    ... 
); 

這是next發揮作用:如果第一個中間件是在請求不感興趣,它可以調用next(這是一個函數)並且該請求將傳遞給第二個中間件(如果該中間件不感興趣,它也可以調用next,將該請求傳遞給應用中的所有中間件,直到中間件處理該請求或者該請求經過,產生404錯誤,因爲沒有找到可以處理請求的中間件)。

passport.authenticate()還返回一箇中間件功能。它通常使用的是這樣的:

router.post('/login', 
    passport.authenticate(...), 
    function (req, res, next) { ... } 
); 

這意味着,如果你看一下堆積例如,passport.authenticate()應該返回接受三個參數reqresnext(事實上,它)的功能。

這意味着,上面的代碼可以寫成這樣:

router.post('/login', function(req, res, next) { 
    passport.authenticate(...)(req, res, next); 
}); 

這在你的問題的代碼相匹配。 爲什麼你想打電話passport.authenticate()就像這是一個相對先進的Passport話題。

編輯:這是什麼passport.authentication,在非常廣泛的術語,是這樣的:

// a function that mimics what `passport.authenticate` does: 
function myAuthenticate() { 
    return function (req, res, next) { 
    ...some stuff... 
    next(); 
    }; 
} 

這是一個功能返回功能。您可以使用它像這樣:

router.post('/login', 
    myAuthenticate(), 
    function (req, res, next) { 
    ... 
    } 
); 

這是(幾乎)與此相同:

router.post('/login', 
    function(req, res, next) { // <-- this is the function that got returned! 
    ...some stuff... 
    next(); 
    }, 
    function(req, res, next) { 
    ... 
    } 
); 
+0

非常感謝您的詳細回答。它幫助我理解語法。但我還有一個問題。 router.post('/ login', passport.authenticate(...), function(req,res,next){...} ); 然後,函數authenticate()返回一個函數,其參數req,res,next。但似乎沒有任何方向讓返回的函數做什麼。 – supergentle

+0

@Supergentle看到我的編輯,我希望它使事情更清楚:) – robertklep

+0

謝謝!它幫助我理解它:D – supergentle