0
0
NestJSframework~5 mins

Why controllers handle incoming requests in NestJS

Choose your learning style9 modes available
Introduction

Controllers in NestJS act like traffic officers. They listen for incoming requests and decide what to do with them.

When you want to respond to a user visiting a webpage or calling an API.
When you need to organize how your app handles different types of requests.
When you want to separate the logic of receiving requests from the logic of processing data.
When building REST APIs to handle GET, POST, PUT, DELETE requests.
When you want to keep your code clean and easy to manage by grouping related request handlers.
Syntax
NestJS
import { Controller, Get, Post } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  findAll() {
    return 'This action returns all cats';
  }

  @Post()
  create() {
    return 'This action adds a new cat';
  }
}

@Controller('route') defines the base route for all methods inside the controller.

Methods inside the controller use decorators like @Get() or @Post() to handle specific HTTP requests.

Examples
This controller handles GET requests to '/dogs' and returns a simple message.
NestJS
import { Controller, Get } from '@nestjs/common';

@Controller('dogs')
export class DogsController {
  @Get()
  getDogs() {
    return 'List of dogs';
  }
}
This controller handles POST requests to '/birds' to add new birds.
NestJS
import { Controller, Post } from '@nestjs/common';

@Controller('birds')
export class BirdsController {
  @Post()
  addBird() {
    return 'New bird added';
  }
}
Sample Program

This controller manages a list of fruits. It returns all fruits on GET requests and adds an orange on POST requests.

NestJS
import { Controller, Get, Post } from '@nestjs/common';

@Controller('fruits')
export class FruitsController {
  private fruits = ['apple', 'banana'];

  @Get()
  getAllFruits() {
    return this.fruits;
  }

  @Post()
  addFruit() {
    this.fruits.push('orange');
    return this.fruits;
  }
}
OutputSuccess
Important Notes

Controllers only handle routing and request reception. Business logic should be in services.

Use decorators to clearly define which HTTP method each controller method handles.

Summary

Controllers listen for and handle incoming requests in NestJS.

They organize routes and connect requests to the right code.

Keep controllers focused on routing; use services for data and logic.