【问题标题】:How do I reach request body in Strapi middleware?如何在 Strapi 中间件中访问请求正文?
【发布时间】:2021-04-19 06:00:04
【问题描述】:

我已经设法让中间件在 Strapi 中工作。但是,我在请求中看不到正文。

在 /middlewares/getEmail/index.js 里面,我有

module.exports = (strapi) => {
  return {
    initialize: function (cb) {
      strapi.app.use(async (ctx, next) => {
        if (ctx.method === "POST" && ctx.url === "/email-leads") {
          console.log(ctx);
        }
        await next();
      });
    },
  };
};

和 ctx 请求日志:

  request: {
    method: 'POST',
    url: '/email-leads',
    header: {
      'content-type': 'application/json',
      accept: 'application/json',
      'user-agent': 'PostmanRuntime/7.26.8',
      'postman-token': 'xxx',
      host: 'localhost:1337',
      'accept-encoding': 'gzip, deflate, br',
      connection: 'keep-alive',
      'content-length': '33'
    }
  },

这是我在此应用程序上编写的唯一中间件。在 /config/middleware.js 中,我有

module.exports = {
  load: {
    before: ["getEmail", "responseTime", "logger", "cors", "responses", "gzip"],
    order: ["parser"],
    after: ["router"],
  },
  settings: {
    getEmail: {
      enabled: true,
    },
  },
};

我阅读了这个 koa-body/unparsed.js 来阅读正文,但 ctx.request 中实际上没有正文。感谢您的帮助。

【问题讨论】:

    标签: node.js post koa strapi


    【解决方案1】:

    如果您在await next(); 行之前console.log(ctx.request.body); 将打印undefined,因为尚未加载正文。所以你有 2 个选项来获取正文。

    1. await next(); 行之后使用console.log(ctx.request.body);
    2. 从原始节点请求加载正文,如下例所示

    Click Here

    【讨论】:

      【解决方案2】:

      所以,我已经找到了解决方案。在这里发布以防其他人需要。

      config/middleware.js,我已经改变了负载,将自定义中间件带到after数组。

        load: {
          before: ["responseTime", "logger", "cors", "responses", "gzip"],
          after: ["parser", "router", "getEmail"],
        },
      

      如果我登录ctxctx.request,我仍然看不到ctx.request.body。但是,如果我直接使用ctx.request.body,如果负载如上写(或parser之后的自定义中间件),我可以到达它。

      【讨论】:

        猜你喜欢
        • 2013-09-05
        • 2016-09-17
        • 2015-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        • 2018-11-27
        • 1970-01-01
        相关资源
        最近更新 更多