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

bookCreating Your First Controller

Swipe um das Menü anzuzeigen

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?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 2

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 2. Kapitel 2
some-alt