Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 387
Nate Gardner Avatar asked Apr 29 '18 00:04

Nate Gardner


People also ask

How do I post on NestJS?

To upload a single file, simply tie the FileInterceptor() interceptor to the route handler and extract file from the request using the @UploadedFile() decorator. Hint The FileInterceptor() decorator is exported from the @nestjs/platform-express package. The @UploadedFile() decorator is exported from @nestjs/common .

How does decorators work in NestJS?

A decorator is an expression that returns a function. It can take a target, name and property descriptor as arguments. We apply a decorator with an @ character and place it at the top of what we are trying to decorate. We can define decorators for class, method or a property. NestJS provides a set of param decorators.

What is @body in NestJS?

To instruct Nestjs that we need the body values from the request, we should use the @Body() decorator function from the @nestjs/common module before the body parameter. Doing this will bind the body values from the request to the body parameter in the createPost() method.

What is a DTO in NestJS?

A DTO is an object that defines how the data will be sent over the network. We could determine the DTO schema by using TypeScript interfaces, or by simple classes. Interestingly, we recommend using classes here.


1 Answers

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

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

like image 79
Nate Gardner Avatar answered Oct 01 '22 18:10

Nate Gardner