You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS Fastify请求体为Buffer未解析为JSON的问题及解决

问题分析与解决方案

这是配置错误导致的问题,核心原因是你启用了rawBody: true配置,同时误用了Express风格的useBodyParser方法(Fastify适配器不支持该方法),最终导致Fastify没有自动解析JSON请求体。

问题根源

  1. 当在NestFactory.create中传入{ rawBody: true }时,Nest会告知Fastify跳过自动解析逻辑,直接返回原始Buffer格式的请求体,这和Express环境下的rawBody行为一致,但Fastify的配置方式和Express不同。
  2. 你调用的app.useBodyParser()是Nest为Express适配器提供的兼容方法,在Fastify环境下不会生效,Fastify有自己的请求体解析配置逻辑。

解决方案

方案1:不需要原始Buffer(大多数场景)

直接移除rawBody: true配置,Fastify会自动解析application/json类型的请求体为JSON对象,此时@Body()能直接拿到解析后的结构,Validation Pipe也能正常工作。

修改后的main.ts核心代码:

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({ logger: true })
    // 移除 { rawBody: true } 配置
  );
  const configService = app.get(ConfigService);
  const port = configService.get('port');
  app.enableCors();
  // 移除 app.useBodyParser() 调用
  app.useGlobalPipes(new ValidationPipe({
    transform: true,
    whitelist: true
  }));
  await app.listen(port);
}

方案2:需要保留原始Buffer(同时获取解析后的JSON)

如果业务需要同时拿到原始Buffer和解析后的JSON,可以通过Fastify原生的bodyParser配置实现,不需要依赖Nest的rawBody参数。

修改后的main.ts核心代码:

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({
      logger: true,
      bodyParser: {
        json: {
          bodyLimit: 10 * 1000 * 1024, // 设置请求体大小限制
          raw: true // 保留原始Buffer到req.rawBody
        }
      }
    })
  );
  const configService = app.get(ConfigService);
  const port = configService.get('port');
  app.enableCors();
  app.useGlobalPipes(new ValidationPipe({
    transform: true,
    whitelist: true
  }));
  await app.listen(port);
}

对应的controller代码:

import { RawBodyRequest } from '@nestjs/common';
import type { FastifyRequest } from 'fastify';

@Post()
async createWallet(
  @Body() body: CreateWalletDto,
  @Req() req: RawBodyRequest<FastifyRequest>
) {
  console.log('解析后的JSON请求体:', body);
  console.log('原始Buffer:', req.rawBody); // 原始Buffer数据
  return 'ok';
}

验证效果

完成配置后,发送application/json类型的请求,@Body()会直接拿到解析后的JSON对象,Validation Pipe可以正常对DTO进行校验和转换。

内容的提问来源于stack exchange,提问作者huy19th

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 11:00:26