快速/连接中间件的控制顺序
我正在尝试添加应该阻止访问部分站点的身份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()
。
- 帕格 – 编译后错误的嵌套 – 包括vs扩展
- 安装Express-on-Railway JS错误
- Express + PassportJs:为什么我们需要在passport策略中用process.nextTick()延迟执行方法?
- RESTful Express Mongoose&Backbone – Backbone model.remove()不起作用
- sailsjs v0.11和express-validator
- 如何从Node.js中的不同应用程序注入模块
- Express.js参数的URL编码,带特殊字符
- NodeJs Express设置一个View来查看呈现为html的文件夹内容
- 使用MailGun从Node.JS发送HTML电子邮件