📖 Scenario: You are building a simple NestJS API to receive user data from a client. The client will send user information in the request body, and your API will process it.
🎯 Goal: Learn how to access and use the request body in a NestJS controller to handle incoming data.
📋 What You'll Learn
Create a controller named UserController
Create a POST route /users in UserController
Use the @Body() decorator to access the request body
Define a DTO class CreateUserDto with name and age properties
Return the received user data from the controller method
💡 Why This Matters
🌍 Real World
APIs often receive data from clients in the request body. Handling this data correctly is essential for creating functional web services.
💼 Career
Understanding how to access and use request body data in NestJS is a fundamental skill for backend developers working with Node.js frameworks.
Progress0 / 4 steps
1
Create the UserController and initial POST method
Create a class called UserController with a method createUser decorated with @Post('users'). Import Controller and Post from @nestjs/common.
NestJS
Hint
Use @Controller() above the class and @Post('users') above the method.
2
Create the CreateUserDto class
Create a class called CreateUserDto with two properties: name of type string and age of type number.
NestJS
Hint
Define the class with the two properties exactly as name: string; and age: number;.
3
Use @Body() to access the request body
In the createUser method, add a parameter called userData decorated with @Body() and typed as CreateUserDto. Import Body from @nestjs/common.
NestJS
Hint
Use @Body() before the parameter and type it as CreateUserDto.
4
Return the received user data
Complete the createUser method by returning the userData parameter.
NestJS
Hint
Simply return the userData parameter from the method.
Practice
(1/5)
1. In NestJS, which decorator is used to access the data sent in the request body?
easy
A. @Body()
B. @Param()
C. @Query()
D. @Headers()
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 A
Quick Check:
Request body data = @Body() [OK]
Hint: Request body data always uses @Body() decorator [OK]
Common Mistakes:
Using @Param() to get body data
Confusing @Query() with @Body()
Trying to access body data without any decorator
2. Which of the following is the correct way to type the request body in a NestJS controller method?
easy
A. create(@Body: any data) {}
B. create(@Body data: any) {}
C. create(@Body() data: any) {}
D. create(@Body data) {}
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.
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 D
Quick Check:
Input name "Alice" produces greeting "Hello, Alice!" [OK]
Hint: Match input keys to typed properties for correct output [OK]
Common Mistakes:
Assuming undefined if typing is missing
Expecting runtime error for missing type
Confusing property names in the body
4. Identify the error in this NestJS controller method:
@Post()
create(@Body data: { age: number }) {
return `Age is ${data.age}`;
}
medium
A. Return statement syntax error
B. Missing parentheses after @Body decorator
C. Incorrect type for data parameter
D. Method should be named differently
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 B
Quick Check:
@Body() needs parentheses [OK]
Hint: Always write @Body() with parentheses, even if empty [OK]
Common Mistakes:
Omitting parentheses after @Body
Misplacing type annotation
Assuming method name causes error
5. You want to accept a request body with optional fields in NestJS. Which method signature correctly types the body to allow optional 'email' and required 'username' fields?
@Post()
create(???) {
// method body
}
hard
A. @Body() data: { username: string; email?: string }
B. @Body() data: { username?: string; email: string }
C. @Body() data: { username: string; email: string }
D. @Body() data: { username?: string; email?: string }
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.