Controller NestJs : The NestJs Journey with Shiv (Part-2)
Controllers
In Nest.js, a controller is a class responsible for handling incoming HTTP requests and providing appropriate responses.
we use @Controller decorator, which indicates this current
class is the controller so when a request comes on a specific route so
controller handles that request. Basically, the controller takes an argument
where you specify the route.
Check the below code where @Controller is a decorator and "cats" in @Controller('cats') which specify a route.
import { Controller, Get } from '@nestjs/common';
@Controller('cats') // Base route for the controller
export class CatsController {
@Get() // Handles GET requests to /cats
findAll(): string {
return 'This is a GET request to /cats';
}
}
Routing:
This base route path acts like a prefix for all the routes defined inside that controller. It helps us group related routes under a common path, making our code more organized and reducing redundancy.
import { Controller, Get } from '@nestjs/common';
@Controller('cats') // Setting the base route path to '/cats'
export class CatsController {
@Get() // This handles GET requests to '/cats'
findAll(): string {
return 'we are all cats';
}
@Get('details') // This handles GET requests to '/cats/details'
findDetails(): string {
return 'All details of cats';
}
}
In simple terms, routing is just a way to specify a route and group routes, just look at the above code. we have two @Get methods in the code. Let me explain
Comments
Post a Comment