如何编写一组常见的中间件

时间:2017-01-09 14:08:11

标签: express middleware

我知道我可以使用方法app.use来包含中间件,或者我可以在我的控制器之前传递中间件

app
.use(middleware1)
.get('/some/path', middlewarePath1, middlewarePath2, (req, res) => {...})

但是如何组成一组常见的中间件?

实施例

var composeMiddleware = compose(middlewarePath1, middlewarePath2)

app
.get('/some/path', composeMiddleware, (req, res) => {...})

1 个答案:

答案 0 :(得分:0)

我会尝试创建包装器中间件

var composeMiddleware = function (req, res, next) {
  console.log('calling first middleware');
  console.log('calling second middleware');
  next();
}

然后使用此

app.get('/some/path', composeMiddleware, (req, res) => {...})

有关自定义中间件的更多信息:https://expressjs.com/en/guide/writing-middleware.html