簡體   English   中英

app.get() 有 3 個參數,我需要一個 explnation Node JS,express

[英]app.get() has 3 parameters, I need an explnation Node JS , express

我是菜鳥。 我有個問題。 我正在使用 passport-google-oauth20

app.get('/auth/google/secrets',
passport.authenticate('google',{failureRedirect: '/login'}),
function(req,res){
  res.redirect('/secrets');
});

你可以清楚地看到,這個 rout ( app.get() ) 有 3 個參數,這是我第一次使用這樣的東西,誰能解釋一下這背后的邏輯/理論?

通常我用

app.get('/somepage' , function(req,res,next){//something});

但在這種特殊情況下,有 3 個參數。 你能為我提供有關這種特定情況的任何文件嗎?

代碼非常好,我只需要一個解釋。

app.get()接受至少兩個 arguments ,如文檔中所示,但您可以根據需要傳遞任意數量的回調(一個或多個):

app.get(path, callback [, callback ...])

您傳遞的每個回調都依次執行。 在第一個調用其處理程序中的next()之前,第二個不會執行,依此類推。

這允許您擁有特定於此路由的中間件。 如果您在問題中顯示,它會插入一些中間件以在執行主請求處理程序之前要求進行身份驗證。

如果身份驗證失敗,中間件將發送響應並且不會調用最終回調。 如果身份驗證通過,它將調用next()並執行最終回調。

這是一個說明性示例:

app.get("/test", 
   (req, res, next) => {
     console.log("in first handler");
     next();
}, (req, res, next) => {
     console.log("in second handler");
     next();         
}, (req, res, next) => {
     console.log("in third handler, sending response");
     // sending response and not calling next()
     res.send("ok");
}, (req, res, next) => {
     // won't ever get here
     console.log("in final handler");
     res.send("hi");
});

這顯示了四個請求處理程序被傳遞給app.get() 服務器調試控制台中的 output 將是:

in first handler
in second handler
in third handler, sending response

並且,此請求的響應將是:

ok

第四個處理程序不會被調用,因為第三個處理程序沒有調用next() 相反,它只是發送對請求的響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM