Detailed Explanation of NestJS Controllers: Handling Different HTTP Request Methods and Route Parameters
- 782Words
- 4Minutes
- 08 Jul, 2024
NestJS is a framework for building efficient, scalable Node.js server-side applications. Controllers are a key part of NestJS, responsible for handling incoming HTTP requests and returning responses. This article will provide a detailed introduction on how to create Controllers in NestJS to handle different HTTP request methods (such as GET, POST, PUT, DELETE), and how to use route parameters and request bodies.
Overview of Controllers
Controllers define routes and handle incoming requests in an application. Each Controller handles a group of related requests, typically associated with a specific resource (such as users, articles, etc.). In NestJS, Controllers are defined through decorators and class methods.
Creating a Controller
In NestJS, a Controller is defined using the @Controller()
decorator. Here is a simple example of a Controller:
1import { Controller, Get } from "@nestjs/common";2
3@Controller("users")4export class UsersController {5 @Get()6 findAll() {7 return "This action returns all users";8 }9}
In the example above, we define a UsersController
class and mark it as a Controller using the @Controller('users')
decorator, setting its route prefix to users
. The findAll
method is marked to handle GET requests using the @Get()
decorator.
Handling Different HTTP Request Methods
NestJS Controllers can handle various HTTP request methods, including GET, POST, PUT, DELETE, etc. Here is an example demonstrating how to handle these request methods in a Controller:
1import {2 Controller,3 Get,4 Post,5 Put,6 Delete,7 Param,8 Body,9} from "@nestjs/common";10
11@Controller("users")12export class UsersController {13 @Get()14 findAll() {15 return "This action returns all users";16 }17
18 @Get(":id")19 findOne(@Param("id") id: string) {20 return `This action returns user with id ${id}`;21 }22
23 @Post()24 create(@Body() createUserDto: CreateUserDto) {25 return "This action adds a new user";26 }27
28 @Put(":id")29 update(@Param("id") id: string, @Body() updateUserDto: UpdateUserDto) {30 return `This action updates user with id ${id}`;31 }32
33 @Delete(":id")34 remove(@Param("id") id: string) {35 return `This action removes user with id ${id}`;36 }37}
In the example above, we define four methods to handle different HTTP request methods:
findAll
handles GET requests and returns all users.findOne
handles GET requests with a route parameter and returns a specific user.create
handles POST requests and creates a new user.update
handles PUT requests with a route parameter and updates a specific user.remove
handles DELETE requests with a route parameter and removes a specific user.
Using Route Parameters
Route parameters are used to pass parameters in the URL. In NestJS, you can retrieve route parameters using the @Param()
decorator. Here is an example:
1import { Controller, Get, Param } from "@nestjs/common";2
3@Controller("users")4export class UsersController {5 @Get(":id")6 findOne(@Param("id") id: string) {7 return `This action returns user with id ${id}`;8 }9}
In the example above, the findOne
method defines a GET request with a route parameter id
using the @Get(':id')
decorator. The @Param('id')
decorator allows us to retrieve the value of the route parameter id
.
Using Request Bodies
Request bodies are used to pass data in the request, typically for POST and PUT requests. In NestJS, you can retrieve request bodies using the @Body()
decorator. Here is an example:
1import { Controller, Post, Body } from "@nestjs/common";2
3class CreateUserDto {4 readonly name: string;5 readonly age: number;6}7
8@Controller("users")9export class UsersController {10 @Post()11 create(@Body() createUserDto: CreateUserDto) {12 return `This action adds a new user with name ${createUserDto.name} and age ${createUserDto.age}`;13 }14}
In the example above, the create
method defines a POST request using the @Post()
decorator. The @Body()
decorator allows us to retrieve the data from the request body, and we use the CreateUserDto
class to enforce type constraints.
Parameter Explanation
@Controller()
: Defines a Controller and specifies the route prefix.@Get()
,@Post()
,@Put()
,@Delete()
: Define routes to handle different HTTP request methods.@Param()
: Retrieves route parameters.@Body()
: Retrieves request bodies.
DTO (Data Transfer Object)
A DTO is an object used to encapsulate request data. In the example above, we define a CreateUserDto
class to encapsulate the data for creating a user:
1class CreateUserDto {2 readonly name: string;3 readonly age: number;4}
Type Constraints for Route Parameters and Request Bodies
By using TypeScript type constraints, we can ensure the correctness of route parameters and request bodies. Here is a comprehensive example demonstrating how to use route parameters and request bodies:
1import { Controller, Get, Post, Put, Param, Body } from "@nestjs/common";2
3class UpdateUserDto {4 readonly name: string;5 readonly age: number;6}7
8@Controller("users")9export class UsersController {10 @Get(":id")11 findOne(@Param("id") id: string) {12 return `This action returns user with id ${id}`;13 }14
15 @Post()16 create(@Body() createUserDto: CreateUserDto) {17 return `This action adds a new user with name ${createUserDto.name} and age ${createUserDto.age}`;18 }19
20 @Put(":id")21 update(@Param("id") id: string, @Body() updateUserDto: UpdateUserDto) {22 return `This action updates user with id ${id}, new name ${updateUserDto.name}, new age ${updateUserDto.age}`;23 }24}
Conclusion
This article provides a detailed introduction to Controllers in NestJS, explaining how to create Controllers to handle different HTTP request methods (such as GET, POST, PUT, DELETE), and how to use route parameters and request bodies.