2017-08-09 106 views
0

我希望快速GET跳過令牌驗證。我想讓每個人都可以發送GET請求,而只需發佈,放置,刪除授權用戶的請求。以下是我的邏輯,但是響應掛起。我試圖使用嵌套的快速使用方法。GET請求的跳過令牌驗證

app.use(function(req, res, next) { 
if (req.method === 'GET') { 

    app.use('/api/someroute', routes); 

} 
else{ 
    //do verification below the next 
    next(); 
    } 
}) 

或有任何其他的方法來處理這個

+0

只需設置您的'GET'路由,然後應用您的令牌認證中間件,任何超出該路由的路由都將受到保護。 – James

+0

我在不同的路徑文件中有超過五十個GET請求,所以在每種方法中我都會遇到困難,但我表示不允許。我想在每個路由 – Developer

+0

中嘗試使用app.use來代替app.get,以便確認您的整個'/ api/someroute'都是'GET'請求? – James

回答

0

就包括所需路線中間件:

var router = express.Router(); 

// no middleware included for get request 
router.get("/route1", handlerRoute1); 
router.get("/route2", handlerRoute2); 

// include some middleware 
router.post("/route3", myMiddleware1, myMiddleware2, handlerRoute3); 
app.use(router); 

凡myMiddleware1和myMiddleware2樣子:

myMiddleware1 = function(req, res, next){ 
    // verify token, etc, .... 

    var success = true; 

    // call next on success 
    if(success) 
     return next(); 
    else 
    { 
     // raise error 
     return res.status(500).json({error: "Missing token..."}); 
    } 
}; 
+0

我想app.use coz有五十個路由,所以router.get(「/ route1 「,handlerRoute1);這將無法正常工作 – Developer

+0

如果方法是得到然後允許如果不是然後驗證令牌 – Developer

0

這是因爲在GET請求的場景中,你實際上並沒有完成請求(或者從中繼續)該中間件)。中間件按順序處理,即先到先服務。如果你只是想保護比GET請求其他一切都那麼這樣的事情就可以了:

app.use(function(req, res, next) { 
    // let GET requests through 
    if (req.method === 'GET') return next(); 

    // perform token auth on all other requests, next() if OK 
}); 
// setup routes 
app.use('/api/someroute', routes); 

你會設置你的中間件第一則聲明你的路由後,這意味着未來的任何請求都必須通過您的令牌檢查,在這種情況下,您只需跳過GET請求。

+0

謝謝詹姆斯,但我提到我想保護職位,並把所有的請求都要求保持不受保護 – Developer

+0

@Developer只是一個錯字,你有沒有嘗試過的代碼? – James