2017-04-12 57 views
0

我正在研究一個大學項目,我們決定去參考MEAN技術堆棧。說實話,我是一個初學者,NodeJSexpress,更確切地說,這是我第一次用它做。 我發現最好使用express.Router,而不是放置所有路線來表示實例,例如app.post('path', function(req, res) { ... })如何將單箇中間件與多個express路由器配合使用?

所以這是我

var express = require('express'); 
var app = express(); 

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

// handles login, doesn't meed autorizationMiddleware 
var authRouter = express.Router(); 
authRouter.route('/login') 
    .post(function (req, res) { 
    ... 
    }); 

// handles fetching of a single, all person(s), fetching of transactions for a person 
var personRouter = require('./routes/personRoutes')(Person, Transaction, autorizationMiddleware); 
//handles adding of a new transaction e.g. POST /api/transactions where params such as sender, recipient and amount are passed in body 
var transactionRouther = require('./routes/transactionRoutes')(Person, Transaction, autorizationMiddleware); 

app.use('/api', authRouter); 
app.use('/api/persons', personRouter); 
app.use('/api/transactions', transactionRoutes); 

app.listen(8080, function() { 
    console.log('Listening on port: ' + 8080); 
}); 

正如你可以看到我有三個路由器(甚至不知道我是否有內[114]與他們太遠),authRouter只處理登錄和我也決定將人的邏輯與交易邏輯分開。 (也許我可以用/api/persons/:personId/transactions的方式處理新交易的創建,但我更喜歡發送所有必需的參數)。

我想問你是否同意我試過的解決方案。正如您所看到的,我正將authrizationMiddleware函數(處理JWT令牌的驗證)功能傳遞給路由器模塊並在那裏使用它。 有沒有更好的方式來使用多個路由器使用相同的中間件,或者這是一種合法的方式?

Thx 乾杯!

回答

0

我不明白你爲什麼使用3 Router s。 「通常」的路線(或者至少我走的路)是將所有路線放在同一個地方,除非路徑非常不同或目的不同(例如,我將錯誤路線與其他路線分開) )。

例如,假設我需要建立一個REST API的應用程序,我可能會像路徑:

/users/:userid 
/users/:userid/comments/:commentid 
/locations 
... 

所有這些途徑可以在同一個Router去,如果你願意,你可以應用特定的認證/授權中間件對他們說:

router.get("https://stackoverflow.com/users/:userid", 
     doAuthentication, authorizeOnUserId, 
     userController.getUserById); 

router.get("/locations", 
     doAuthentication, authorizeLocations, 
     locationController.getAllLocations); 

的中間件被稱爲序列和請求上只如果沒有錯誤,下一個中間件(unauthenticaed/unhauthorized)通過。 然後,你可以簡單地導入您的路線是這樣的:

app.use('/api', router); 

使用這種技術可以讓你有超過你的路由細粒度控制。 希望這有助於。

相關問題