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

bookCreating Your First Controller

Svep för att visa menyn

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 5

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 5
some-alt