import { Controller, Post, Body } from '@nestjs/common';
import { MyService } from 'my.service';
import { MyDto } from './dto/my.dto';
@Controller('my-route')
export class MyController {
constructor(private readonly _myService: MyService) {}
@Post()
async myMethod(@Body() myDto: MyDto) {
console.log(myDto); // undefined
return await this._myService.doStuff(myDto.elementOfInterest); // Passes undefined variable into method.
}
}
我对在Nest中从POST请求中访问表单数据的正确方式感到困惑。文档和示例都展示了在参数名之前使用@Body()
装饰器来简单地获取整个请求体(或者如果使用参数,则是请求体中的特定元素)。然而,在上面的示例中,请求体从未被填充,调用方法时myDto
的值为undefined。即使将其类型更改为字符串并仅在POST的请求体中传递单个键/值对,也会导致其值为undefined。
在Nest中处理POST请求体的正确方法是什么?
Pipe
或Interceptor
吗?我刚从一个空白的 Nest 项目中进行了快速检查,创建了一个带有@Body()
参数的@Post()
控制器,并且按预期工作。编辑 - 我刚刚尝试了你的确切代码,没有 MyDto 和 MyService,它也可以工作。你使用的是哪个版本的 NestJS? - VinceOPSContent-Type
设置为application/json
。 - Kamil Myśliwiec