NodeJS中的奇怪的express.use()行为

时间:2014-02-18 13:10:40

标签: javascript node.js express

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。怎么了?怎么解决这个问题?

2 个答案:

答案 0 :(得分:2)

原因是,一旦你申报了一条路线,Express就会(在引擎盖下)将路由器中间件插入中间件链。这意味着任何传入的请求都将由路由器处理,并且(可能)不会传递给路由器/路由之后声明的任何中间件。

@ jgitter关于在路由声明中包含中间件的建议将正常工作。

另一个选择是使用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(); });

答案 1 :(得分:1)

这对我来说是正确的,我不确定为什么它不能随便工作。作为一种解决方法,您可以改为:

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 */ });

您还可以将装载路径作为可选的第一个参数添加到app.use()方法。