What are controllers? Controllers in Nest.js are classic TypeScript classes that are decorated with the
@Controller() decorator. In such classes, methods corresponding to HTTP operations such as GET, POST, PUT, DELETE are defined, where each method within the controller is decorated with a corresponding HTTP decorator. Example of a simple controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
import { Controller, Get, Post, Body, Param } from '@nestjs/common'; @Controller('users') export class UsersController { private users = []; @Get() findAll(): any[] { return this.users; } @Get(':id') findOne(@Param('id') id: string): any { return this.users.find(user => user.id === id); } @Post() create(@Body() user: any): string { this.users.push(user); return 'User created successfully'; } } |
In this example, … Read more