What is Controller in NestJS: Definition and Usage
controller is a class responsible for handling incoming HTTP requests and returning responses. It acts like a traffic manager, directing requests to the right service or logic inside your app.How It Works
Think of a NestJS controller as a receptionist in an office. When someone (a client) sends a request, the receptionist listens and decides what to do with it. The controller receives the request, understands what is needed, and then calls the right service or function to handle the task.
Controllers use decorators like @Controller() to define the route path and @Get(), @Post(), etc., to specify how to respond to different HTTP methods. This setup helps organize your app by separating the request handling from the business logic.
Example
This example shows a simple NestJS controller that responds to a GET request at the root path with a welcome message.
import { Controller, Get } from '@nestjs/common'; @Controller() export class AppController { @Get() getHello(): string { return 'Hello from NestJS controller!'; } }
When to Use
Use controllers whenever you need to handle HTTP requests in your NestJS app. They are perfect for building APIs, web apps, or any server-side logic that responds to client requests.
For example, if you build a blog, controllers handle requests like fetching posts, creating new posts, or deleting posts. They keep your app organized by separating how requests are received from how data is processed.
Key Points
- Controllers handle incoming HTTP requests and send responses.
- They use decorators to define routes and HTTP methods.
- Controllers separate request handling from business logic.
- They keep your application organized and maintainable.