NodeJS 如何访问Fastify请求的原始正文?

nzk0hqpo  于 11个月前  发布在  Node.js
关注(0)|答案(4)|浏览(121)

正如你所想象的,我对Express很熟悉,但这是我第一次使用Fastify。
我想访问一个Fastify请求的 unmodified body,用于webhook的签名验证-即,我想看到请求进来时没有被任何中间件修改。在Express中,这通常是通过访问request.rawBody来完成的。

如何访问Fastify请求的原始正文?

6bc51xsx

6bc51xsx1#

您也可以查看此社区插件:https://github.com/Eomm/fastify-raw-body
如果您使用的是Typescript & fastify/autoload,请将其放置到plugins/rawbody.ts:

import fp from "fastify-plugin";

import rawbody, { RawBodyPluginOptions } from "fastify-raw-body";

export default fp<RawBodyPluginOptions>(async (fastify) => {
  fastify.register(rawbody, {
    field: "rawBody", // change the default request.rawBody property name
    global: false, // add the rawBody to every request. **Default true**
    encoding: "utf8", // set it to false to set rawBody as a Buffer **Default utf8**
    runFirst: true, // get the body before any preParsing hook change/uncompress it. **Default false**
    routes: [], // array of routes, **`global`** will be ignored, wildcard routes not supported
  });
});

字符串
由于global:false我们需要在特定的处理程序中配置它:

fastify.post<{ Body: any }>(
    "/api/stripe_webhook",
    {
      config: {
        // add the rawBody to this route. if false, rawBody will be disabled when global is true
        rawBody: true,
      },
    },

    async function (request, reply) {
...


然后,您可以使用request.rawBody访问处理程序中的原始主体

xfb7svmp

xfb7svmp2#

备注:Fastify请求只能有req.body -它们不能像其他Web服务器(例如Express)那样有req.body和req.rawBody。这是因为addContentTypeParser()只返回修改后的body,它不能向请求添加任何其他内容。

相反,在内容类型解析器中,我们 * 只 * 添加到一个路由,我们做:

  • req.body.parsed(对象,与通常在req.body中的内容相同)
  • req.body.raw(字符串)

更多信息请参见GitHub和addContentTypeParser()文档。

server.addContentTypeParser(
    "application/json",
    { parseAs: "string" },
    function (req, body, done) {
      try {
        var newBody = {
          raw: body,
          parsed: JSON.parse(body),
        };
        done(null, newBody);
      } catch (error) {
        error.statusCode = 400;
        done(error, undefined);
      }
    }
  );

字符串

fdbelqdn

fdbelqdn3#

GitHub上的rawBody支持有问题
还有一个模块:"raw-body"。要在Fastify中使用这个模块:

const rawBody = require('raw-body')

fastify.addContentTypeParser('*', (req, done) => {
    rawBody(req, {
        length: req.headers['content-length'],
        limit: '1mb',
        encoding: 'utf8', // Remove if you want a buffer
    }, (err, body) => {
        if (err) return done(err)
        done(null, parse(body))
    })
})

字符串
我希望我能帮助你,我也是新的fastify

n3ipq98p

n3ipq98p4#

根据文档https://docs.nestjs.com/faq/raw-body
在main.ts中

const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
    {
      rawBody: true,
    },
  );

字符串
然后在您的控制器中

async handleStripeEvent(
    @Headers('stripe-signature') signature: string,
    @Req() request: RawBodyRequest<FastifyRequest>,
  ) {
    if (!signature) {
      throw new BadRequestException('Missing stripe-signature header');
    }

    const event = await this.webhooksService.handleStripePaymentWebhook(
      signature,
      request.rawBody,
    );
  }

相关问题