The request body holds data sent by a client to the server, often used to send information like form inputs or JSON data.
Request body in NestJS
import { Controller, Post, Body } from '@nestjs/common'; @Controller('example') export class ExampleController { @Post() create(@Body() data: any) { return data; } }
The @Body() decorator extracts the request body data.
You can type the data parameter to match the expected data shape.
import { Controller, Post, Body } from '@nestjs/common'; @Controller('users') export class UsersController { @Post('create') createUser(@Body() userData: { name: string; age: number }) { return `User ${userData.name} is ${userData.age} years old.`; } }
import { Controller, Post, Body } from '@nestjs/common'; @Controller('messages') export class MessagesController { @Post() saveMessage(@Body() message: string) { return `Message received: ${message}`; } }
This controller handles POST requests to '/products/add'. It reads the product name and price from the request body and returns a confirmation string.
import { Controller, Post, Body } from '@nestjs/common'; @Controller('products') export class ProductsController { @Post('add') addProduct(@Body() product: { name: string; price: number }) { return `Added product: ${product.name} with price $${product.price}`; } }
Always validate and sanitize request body data to keep your app safe.
Use DTOs (Data Transfer Objects) with classes and validation decorators for better structure.
Request body is usually used with POST, PUT, or PATCH HTTP methods.
The request body carries data sent from client to server.
Use @Body() decorator in NestJS to access this data.
Typing the body helps catch errors and improves code clarity.
Practice
Solution
Step 1: Understand the purpose of decorators in NestJS
Decorators like @Body(), @Param(), @Query(), and @Headers() extract different parts of the request.Step 2: Identify which decorator accesses the request body
@Body() specifically extracts the data sent in the request body from the client.Final Answer:
@Body() -> Option AQuick Check:
Request body data = @Body() [OK]
- Using @Param() to get body data
- Confusing @Query() with @Body()
- Trying to access body data without any decorator
Solution
Step 1: Recall the syntax for decorators with typed parameters
In NestJS, the decorator is followed by parentheses and the parameter is typed after the colon.Step 2: Check each option's syntax
create(@Body() data: any) {} correctly uses @Body() with typed parameter 'data: any'. Options B, C, and D have syntax errors or missing parentheses.Final Answer:
create(@Body() data: any) {} -> Option CQuick Check:
Correct decorator syntax = create(@Body() data: any) {} [OK]
- Omitting parentheses after @Body
- Placing type before parameter name
- Not typing the parameter at all
@Post()
create(@Body() data: { name: string }) {
return `Hello, ${data.name}!`;
}Solution
Step 1: Understand the method behavior with typed body
The method expects an object with a 'name' string property and returns a greeting using that name.Step 2: Analyze the input and output
The client sends {"name": "Alice"}, so data.name is "Alice". The method returns "Hello, Alice!".Final Answer:
"Hello, Alice!" -> Option DQuick Check:
Input name "Alice" produces greeting "Hello, Alice!" [OK]
- Assuming undefined if typing is missing
- Expecting runtime error for missing type
- Confusing property names in the body
@Post()
create(@Body data: { age: number }) {
return `Age is ${data.age}`;
}Solution
Step 1: Check the decorator syntax
@Body decorator requires parentheses even if empty, so it should be @Body()Step 2: Verify other parts of the method
The type and return statement are correct; only the decorator syntax is wrong.Final Answer:
Missing parentheses after @Body decorator -> Option BQuick Check:
@Body() needs parentheses [OK]
- Omitting parentheses after @Body
- Misplacing type annotation
- Assuming method name causes error
@Post()
create(???) {
// method body
}Solution
Step 1: Understand optional and required fields in TypeScript types
A question mark (?) after a property name means it is optional; absence means required.Step 2: Match the requirement to the type
Username is required, so no '?'. Email is optional, so it has '?'. @Body() data: { username: string; email?: string } matches this.Final Answer:
@Body() data: { username: string; email?: string } -> Option AQuick Check:
Required username, optional email = @Body() data: { username: string; email?: string } [OK]
- Marking required fields as optional
- Marking optional fields as required
- Forgetting to use @Body() decorator
Ready to prove it?
Pass the test and this pattern moves unknown
