如何解决NestJS中@Body()始终为undefined的问题
NestJS @Body() 和 @Req() 始终为 undefined 的排查方案
1. 先确认请求本身是否正确
- 确保Postman中请求方式为POST,请求体选择
Raw > JSON格式,而非form-data或x-www-form-urlencoded。 - 检查请求体的JSON语法合法性:键名必须用双引号,不能有多余的逗号。示例合法请求体:
{ "username": "your-username", "password": "your-password" } - 用curl测试排除Postman问题:
curl -X POST http://localhost:3000/api/auth/login \ -H "Content-Type: application/json" \ -d '{"username":"test","password":"123456"}'
2. 显式添加JSON解析中间件
NestJS默认会自动加载Express的json()中间件,但有时会因配置异常失效,手动添加试试:
在main.ts的bootstrap函数中,app.enableCors()之后添加:
import { json } from 'express'; // ... app.use(json());
3. 排查全局管道/拦截器影响
如果AppModule中注册了全局管道(比如ValidationPipe),暂时注释掉测试:
// 注释掉这段全局管道配置 // { // provide: APP_PIPE, // useClass: ValidationPipe, // },
若注释后能正常获取请求体,说明管道配置有问题。调整ValidationPipe参数,比如关闭严格白名单检查:
{ provide: APP_PIPE, useValue: new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: false, // 先禁用该选项 }), }
4. 调整数据库初始化顺序
当前代码先完成数据库迁移再启动服务,可能导致服务启动异常。将数据库初始化逻辑移到app.listen()之后:
async function bootstrap() { const app = await NestFactory.create(AppModule); // ... 其他配置 await app.listen(port); // 数据库初始化移到服务启动后 await appDataSource.initialize(); await appDataSource.runMigrations(); const schemas = await appDataSource.query( 'select schema_name as name from information_schema.schemata;', ); for (let i = 0; i < schemas.length; i += 1) { const { name: schema } = schemas[i]; if (schema.startsWith('tenant_')) { const tenantId = schema.replace('tenant_', ''); const connection = await getTenantConnection(tenantId); await connection.runMigrations(); await connection.close(); } } }
5. 确认@Req()导入正确性
确保@Req()是从@nestjs/common导入,而非Express的Request对象:
import { Req } from '@nestjs/common'; // 正确导入
内容的提问来源于stack exchange,提问作者Michael Adlhoch
相关产品推荐
相关产品推荐

