簡體   English   中英

NestJS - 如何使用 @Body() 裝飾器訪問帖子正文?

[英]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未定義的情況下調用該方法。 即使將其類型更改為字符串並簡單地在我的 POST 正文中傳遞單個鍵/值對,也會使其未定義。

在 Nest 中處理 POST 正文的正確方法是什么?

Kamil Mysliwiec 關於Content-Type的評論就是解決方案。

另外,請記住將Content-Type請求標頭設置為application/json

萬一有人偶然發現我的問題。 我也有這個問題,但對我來說是在main.ts的服務器設置中。

我將此代碼設置為包含與 https 一起使用的 ssl 證書,但僅在生產中使用

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的服務器會破壞它。

所以我把它改成了這樣的,因為它適用於 undefined

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

或者做這樣的事情,因為我不知道將選項設置為 undefined 是否安全

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

希望這可以幫助有類似問題的人

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM