Creating 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.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Creating Your First Controller
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.
Tack för dina kommentarer!