【问题标题】:How to invoke multiple express middlewares manually如何手动调用多个 express 中间件
【发布时间】:2019-11-03 12:13:19
【问题描述】:

我有一种情况,我想调用多个 express 中间件取决于请求负载。

这些中间件是从 express 验证器 checkSchema 生成的 方法。

所以我编写了一个可以访问请求对象的中间件,我可以从请求有效负载中读取一个属性,然后决定必须运行哪个模式。

一个实现应该是这样的。

let app = express();

let schema1 = checkSchema({
  field1: {
    in: ["body"],
    exists: {
      errorMessage: "field1 is missing",
    }
  }
});

let schema2 = checkSchema({
  field2: {
    in: ["body"],
    exists: {
      errorMessage: "field 2 is missing",
    }
  }
});

app.post("/resource", (req, res, next) => {
  if(req.body.type === "TYPE1") {
    // Invoke schema1 middleware
  }
  if(req.body.type === "TYPE2") {
    // Invoke schema2 middleware
  }
});

这里的 schema1 和 schema 2 不是单一的中间件。它是一个 中间件数组。

如果是中间件,我可以调用 schema1(req, res, next);

如果有人经历过这个,请建议我手动运行中间件数组的方法是什么。

【问题讨论】:

    标签: node.js express express-validator


    【解决方案1】:

    我已经发布了express-validator v6.0.0,这应该有助于解决这类问题。

    现在有一个.run(req) 方法,它应该让你do things with express-validator in an imperative way。

    对于您的用例,您可以执行以下操作:

    app.post("/resource", async (req, res, next) => {
      if(req.body.type === "TYPE1") {
        await Promise.all(schema1.map(chain => chain.run(req)));
      }
      if(req.body.type === "TYPE2") {
        await Promise.all(schema2.map(chain => chain.run(req)));
      }
    });
    

    从checkSchema returns an array of validation chains 开始,代码将它们中的每一个映射到各自的执行承诺。
    当所有的 Promise 都完成后,你的代码可以继续执行并做任何你想做的事情。也许检查validationResult 是否有错误,相应地呈现不同的页面等等——由你决定!

    【讨论】:

      【解决方案2】:

      根据这个问题Use an array of middlewares at express.js有一个repo:https://github.com/blakeembrey/compose-middleware:

      根据自述文件:

      app.use(compose([
        function (req, res, next) {},
        function (err, req, res, next) {},
        function (req, res, next) {}
      ]))
      

      那么,你可以做的是:

      app.post("/resource", (req, res, next) => {
        if(req.body.type === "TYPE1") {
          compose(schema1)(req,res,next);
        }
        if(req.body.type === "TYPE2") {
          compose(schema2)(req,res,next);
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-31
        • 1970-01-01
        • 1970-01-01
        • 2021-02-23
        • 2019-07-05
        相关资源
        最近更新 更多