NestJS - 如何使用@Body() 装饰器访问 post 主体?

NestJS - How to access post body using @Body() decorator?

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 未定义的情况下调用该方法。即使将其类型更改为字符串并简单地将单个 key/value 对传递到我的 POST 的正文中,它仍未定义。

在 Nest 中处理 POST 实体的正确方法是什么?

Kamil Mysliwiec 关于 Content-Type 的评论是解决方案。

Also, keep in mind to set Content-Type request header into application/json.

以防有人无意中发现我的问题。 我也有这个问题,但对我来说是在 main.ts.

的服务器设置中

我将此代码设置为包含 ssl 证书以使用 https,但仅在生产环境中使用

let serverOptions = null;
if (environment.production) {
    const httpsOptions = {
        key: fs.readFileSync(environment.sslKeyPath),
        cert: fs.readFileSync(environment.sslCertPath),
    };

    serverOptions = { httpsOptions };
}
const app = await NestFactory.create(AppModule, serverOptions)

但显然创建带有选项 null 的服务器会破坏它。

所以我把它改成这样,因为它适用于未定义的

const app = await NestFactory.create(AppModule, serverOptions ?? undefinded)

或者做这样的事情,因为我不知道将选项设置为未定义是否安全

const app = serverOptions ? await NestFactory.create(AppModule, serverOptions) : await NestFactory.create(AppModule)

希望这对遇到类似问题的人有所帮助