Controllers in NestJS
Learn how to use a controller to handle routing in NestJS application.
Controllers are responsible for processing incoming HTTP requests and returning the appropriate HTTP responses. In essence, controllers act as an intermediary between the client and the rest of the application, handling the request-response process and ensuring they send the appropriate response back to the client.
Using the @Controller
decorator to define a controller
To create a new controller related to students in our school management system, we can define a new class and use the @Controller('students')
decorator to specify the base URL for the endpoint associated with the controller.
import { Controller } from '@nestjs/common';@Controller('students')export class StudentsController {// Controller methods go here}
Using various HTTP request decorators
NestJS provides decorators for different HTTP request methods to define handlers for specific requests. Here are some examples:
The @Get
request
In a NestJS controller, we can use the @Get()
decorator to define a GET
endpoint, which maps the decorated method to the GET
HTTP method and allows us to retrieve data from the server.
import { Controller, Get } from '@nestjs/common';@Controller('students')export class StudentsController {private students = [];@Get()findAll(): string {return this.students;}}
In the above code, we define a GET
endpoint for the ...