快速/连接中间件的控制顺序

我正在尝试添加应该阻止访问部分站点的身份validation中间件:

app = express() .get('/api/test', function (req, res) { ... }) .use('/api', function (req, res, next) { if (req.param('key')) { next(); } else { res.json(401, { message : 'Authentication failed' }); res.end(); } }) .get('/api/data', function (req, res) { ... }); 

而且我期望调用/ api / data将首先由关键检查器处理,然后(如果成功)由/ api / data处理程序处理。 而是首先处理'/ api / data'的请求。

看来,检查器的工作/ api / something_that_does_not_exist,但不是/ api / something_that_exist。

也许我错过了快递/连接文件的东西?

更新我跟踪了这​​个事实,第一个get / post调用初始化路由器中间件,所以它首先被执行。

一旦你声明了一个路由,Express在设置应用的时候将router中间件插入到中间件堆栈中。

在你的情况下,因为你插入.get('/api/test', ...)之前插入你的密钥检查中间件,路由器中间件被插入,并将优先(也适用于/api/data ),你的关键检查是从来没有被称为。

这里有两个解决scheme:

 // separate middleware, used for all routes that need checking var keyChecker = function(req, res, next) { ... }; app.get('/api/test', function(req, res) { ... }); app.get('/api/data', keyChecker, function(req, res) { ... }); // or, as an alternative, create a 'catch-all' route between the routes that don't // need to be checked, and the ones that should; this will also match non-existing // routes (like '/api/foobar'), which might or might not be an issue; app.get('/api/test', function(req, res) { ... }); app.all('/api/*', function(req, res, next) { // 'all' means 'all methods' // keychecker code }); app.get('/api/data', function(req, res) { ... }); 

第三个解决scheme可以是显式检查密钥检查中间件本身req.path === '/api/test'req.path === '/api/test' ),如果匹配,就调用next()