Nate Gardner
Nate Gardner

Reputation: 1717

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?

Upvotes: 25

Views: 46342

Answers (3)

kevtae
kevtae

Reputation: 11

Also, make sure it's a Post request instead of get.

Upvotes: 0

Equilibrium
Equilibrium

Reputation: 63

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

Upvotes: 3

Nate Gardner
Nate Gardner

Reputation: 1717

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

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

Upvotes: 38

Related Questions