Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære What Are Controllers in Nest.js | Controllers and Routing
Building Backend Applications with Nest.js

bookWhat Are Controllers in Nest.js

Sveip for å vise menyen

Controllers are responsible for handling incoming requests and returning responses.

When a client sends a request to your server, the controller receives it and decides what should happen next.

In Nest.js, controllers are defined using decorators. A decorator tells Nest how a class or method should behave.

For example:

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

@Controller('users')
export class UsersController {
  @Get()
  getAllUsers() {
    return 'List of users';
  }
}

In this example:

  • @Controller('users'): defines the base route;
  • @Get(): handles GET requests;
  • getAllUsers(): returns a response.

When you open /users in the browser, this method is executed.

Controllers should stay simple. Their job is to:

  • Receive the request;
  • Call the appropriate logic;
  • Return a response.

They should not contain complex logic. That logic belongs in services.

question mark

What is the main responsibility of a controller in Nest.js?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 1

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 2. Kapittel 1
some-alt