Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Creating Your First Controller | Section
Building Backend Applications with Nest.js

bookCreating Your First Controller

Desliza para mostrar el menú

Open the src folder and create a new file:

users.controller.ts

Add the following code:

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

@Controller('users')
export class UsersController {
  @Get()
  getAllUsers() {
    return 'Users route';
  }
}

This controller handles requests to the /users route.

Here is what is happening:

  • @Controller('users'): sets the base route for this controller;
  • @Get(): handles GET requests;
  • getAllUsers(): runs when the route is accessed and returns a response.

Now register the controller in your module.

Open app.module.ts and update it:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersController } from './users.controller';

@Module({
  imports: [],
  controllers: [AppController, UsersController],
  providers: [AppService],
})
export class AppModule {}

  • controllers: registers all controllers used in the app;
  • UsersController: makes the new route available;
  • AppController: remains as the default controller.

Now restart your server and open:

http://localhost:3000/users

You will see the response from your controller.

question mark

What decorator defines the base route for a controller?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 5

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 1. Capítulo 5
some-alt