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?
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 .
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.
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.
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.
Kamil Mysliwiec's comment about Content-Type
was the solution.
Also, keep in mind to set
Content-Type
request header intoapplication/json
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With