简体   繁体   中英

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.
    }
}

I'm confused about the proper way to access the body form data from a POST in Nest. The documentation and examples all show simple use of the @Body() decorator preceding the name of a parameter which will contain the body (or a specific element in the body if a parameter is used). Yet in my example above, the body is never populated, and the method is called with myDto being undefined. Even changing its type to a string and simply passing a single key/value pair in the body of my POST leaves it undefined.

What's the correct way to handle POST bodies in Nest?

Kamil Mysliwiec's comment about Content-Type was the solution.

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

In case anyone stumbles on my problem. I had this issue too, but for me was it in the server setup in the main.ts .

I set this code to include a ssl certificate to work with https, but only in production

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)

but apparently creating a server with options null , will break it.

So I changed it to something like this, since it works with undefined

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

alternatively do something like this, cause I don't know if setting the options to undefined is safe

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

Hope this helps someone with a similar problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM