第一个控制器

The Controllers layer is responsible for handling incoming HTTP requests. In Nest, Controller is a simple class with @Controller() decorator.

控制层负责处理传入的HTTP请求。在Nest中,控制器是一个带有@Controller()装饰器的类。

图片标题

In previuos section we set up entry point for an application. Now, let's build our first endpoint /users:

上一章节中,我们已经设置好了入口点。现在,让我们开始构建我们的第一个路径/users

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

@Controller()
export class UsersController {
    @Get('users')
    getAllUsers() {}

    @Get('users/:id')
    getUser() {}

    @Post('users')
    addUser() {}
}

As you can guess, we created an endpoint with 3 different paths:

如你所想,我们已经创建好了三种不同的路径:

GET: users
GET: users/:id 
POST: users

It is not necessary to repeat 'users' in each path. Nest allows us to pass additional metadata to @Controller() decorator. The path, which is a prefix for each route. Let's rewrite our controller:

不需要在每个路径中都重复'users'。 Nest允许我们向@Controller()装饰器传递额外的元数据。路径就是每个路由的前缀。让我们重写我们的控制器。

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

@Controller('users')
export class UsersController {
    @Get()
    getAllUsers() {}

    @Get('/:id')
    getUser() {}

    @Post()
    addUser() {}
}

路由

Let's stop for a while. We setup routes, but they are not doing anything. We don't have any persistence, so we also do not have any user. What's now? For explanation purposes, I will use a fake data:

我们暂停一会会。我们设置路由,但是路由并没有起到任何作用。我们没有持久层,也没有用户,那么我们接下来要做什么呢?

@Get()
getAllUsers(req, res, next) {
    res.status(HttpStatus.OK).json([{
        id: 1, name: 'Test'
    }]);
}

As you can see, methods in Nest controllers have the same behaviour as a simple routes in Express.

如你所见,Nest控制器的方法和Express的简单路由有着相同的行为。

If you want to learn more about req (request), res (response) and next you should read short Express Routing - Documentation. In Nest, they work equivalently. Furthermore, you can use @types/express package:

如果你想了解更多关于req(request)res(response)next的信息,你可以阅读Express Routing - 文档。在Nest中,他们是等价的。此外,你还可以使用@types/express包。

import { Request, Response, NextFunction } from 'express';

@Controller('users')
export class UsersController {
    @Get()
    getAllUsers(req: Request, res: Response, next: NextFunction) {}
}

Moreover, Nest provides a set of custom decorators, which you can use to mark arguments.

Nest还提供了一套可以用来标记参数的自定义装饰器。

Nest Express
@Request() / @Req() req
@Response() / @Res() res
@Next() next
@Session() req.session
@Param(param?: string) req.params[param]
@Body(param?: string) req.body[param]
@Query(param?: string) req.query[param]
@Headers(param?: string) req.headers[param]

This is how you can use them:

以下是使用自定义装饰器的方法:

@Get('/:id')
public async getUser(@Response() res, @Param('id') id) {
    const user = await this.usersService.getUser(id);
    res.status(HttpStatus.OK).json(user);
}

Remember to import decorators at the beginning of a file:

记住在文件开始位置导入装饰器:

import { Response, Param } from '@nestjs/common';
Important! If you want to use:
@Session() - install express-session
@Body() - install body-parser

Last Step

UsersController is ready to use, but our module doesn't know about it yet. Let's open ApplicationModule and add some metadata.

现在已经可以使用UsersController了,但是我们的模块还没意识到UsersController可以使用。让我们打开ApplicationModule并添加一些元数据。

import { Module } from '@nestjs/common';
import { UsersController } from "./users.controller";

@Module({
    controllers: [ UsersController ]
})
export class ApplicationModule {}

As you can see - we only have to insert our controller into controllers array. It's everything.

如你所见--我们只需将控制器插入控制器数组中。

results matching ""

    No results matching ""