首页 > 解决方案 > 如何在 Strapi 中间件中访问请求正文?

问题描述

我设法使中间件在 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.jspostkoastrapi

解决方案


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

config/middleware.js中,我改变了负载,将自定义中间件放入after数组中。

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

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


推荐阅读