在NodeJS中奇怪的express.use()行为
app.use(function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.get('/2',function(req,res){ console.log('/2'); res.end(); }); ...
有用。 在/ 1和/ 2请求上执行中间件。
现在我希望中间件不会在请求页面1上执行,但在下面的所有页面上:
app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.use(function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/2',function(req,res){ console.log('/2'); res.end(); }); ...
在这种情况下,中间件不会执行。 即使在请求页面/ 2。 怎么了? 如何解决这个问题?
原因是,一旦你声明了一个路由,Express将(在引擎盖下)将路由器中间件插入到中间件链中。 这意味着任何传入的请求都将被路由器处理,并且(可能)不会传递到在路由器/路由之后声明的任何中间件。
@ jgitter在路由声明中包含中间件的build议将工作得很好。
另一个select是使用app.all
而不是app.use
:
app.get('/1',function(req,res){ console.log('/1'); res.end(); }); app.all('*', function(req,res,next){ console.log('middleware executed'); next(); }); app.get('/2',function(req,res){ console.log('/2'); res.end(); });
这对我来说是正确的,我不知道为什么它不能正常工作。 作为解决方法,您可以这样做:
var middleware = function (req, res, next) { // do things next(); }; app.get('/1', middleware, function(req, res) { /* handle request */ }); app.get('/2', function(req, res) { /* handle request */ });
您也可以将一个装载path作为可选的第一个参数添加到app.use()方法中。