2015-03-31 59 views
0

我在Express中定義靜態&動態路由,並且我構建了一個通用響應程序來發送響應給客戶端。響應者對所有路線都是全球性的,因此在最後添加。快速動態路由的獲取添加到靜態路由中間件堆棧

但是,當我定義靜態路由時,動態路由的中間件在響應者之前被添加到棧中。

爲了說明:響應中間件被調用之前: '頁/你好/'

server.get('/hello/test', function(req, res, next) { 
    console.log('/hello/test'); 
    next(); 
}); 
server.get('/hello/:page', function(req, res, next) { 
    console.log('/hello/:page'); 
    next(); 
}); 
server.use(function(req, res, next) { 
    res.status(200).send('test'); 
}); 

調用curl localhost:3000/hello/test將CONSOLE.LOG兩個 '/你好/測試' 和。我只想要調用第一個匹配路由中間件。

反正有防止這種行爲嗎?

+0

你試圖刪除'next();'從第一條路線? - > http://expressjs.com/api.html#app.METHOD – 2015-03-31 13:03:09

+0

@John我將如何到達沒有next()的響應中間件? – lohfu 2015-03-31 13:14:35

回答

0

方法next()將控件傳遞給下一個處理函數。 你可以解決您的問題,只是從你的路由去掉next()調用,並把中間件成一個函數:

server.get('/hello/test', myMiddleware(req, res, next), function(req, res) { 
    console.log('/hello/test'); 
}); 
server.get('/hello/test_b', myMiddleware(req, res, next), function(req, res) { 
    console.log('/hello/test_b'); 
}); 
server.get('/hello/:page', myMiddleware(req, res, next), function(req, res) { 
    console.log('/hello/:page'); 
}); 
server.get('*', myMiddleware(req, res, next), function (req, res) { 
    res.type('txt').send('Not found'); 
}); 


function myMiddleware(req, res, next) { 
    console.Log("in midleware") 
    next(); 
}