在同一个文件中写中间件
可以如下使用中间件:
var middleware = {
requireAuthentication: function(req, res, next) {
console.log('private route list!');
next();
},
logger: function(req, res, next) {
console.log('Original request hit : '+req.originalUrl);
next();
}
}
app.get('/', [middleware.requireAuthentication, middleware.logger], function(req, res) {
res.send('Hello!');
});
https://stackoverflow.com/a/36649698/3054511
把中间件写在单独的模块中
文件:my-middleware.js
module.exports = function(options) {
return function(req, res, next) {
// Implement the middleware function based on the options object
next()
}
}
使用这个中间件:
var mw = require('./my-middleware.js')
app.use(mw({ option1: '1', option2: '2' }))
这样实现中间件有两个好处:
- 模块化
- 中间件可以接收参数,实现更加灵活。