NestJS Controller learning

Controller Introduction

The role of the Controller is mainly to accept processing requests and return processed response data to the client. There are many routes in the Controller, and the routes mainly perform different business logic processing.

routing

When we write Controller, we can use @Controller()decorator to define the corresponding Controller. In decorators we can use path prefixes to group routes to minimize duplication of code. For example, we can put all the related routes of product information management in a controller, the specific code is as follows:

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

@Controller("commodity")
export class CommodityController {
    
    
  @Get()
  getCommodity(): string {
    
    
    return "获取商品";
  }

  @Post("/save")
  saveCommodity(): string {
    
    
    return "保存商品";
  }
}

In the above code, we declared commoditythe prefixed controller, so NestJs will add commoditykeywords at the beginning of the routing address when generating routes for us.

The specific routing generation is determined according to the request decorator in the controller code block. For example, in the above code, we declare two methods for receiving requests, one is the request, and uses the default routing method, and the other Getis PostRequest, and declare the specific path address /save.

So NestJs will help me generate the following two request paths: GET /commodityand POST /commodity/save. In this way, when we send requests to these two addresses, the reason will go to these two routes for subsequent business logic processing.

In this way, we can know that the path production rules of NestJs are: 前缀 + 具体路径.

Note: In NestJS, when using the NestJs built-in request method, you need to pay attention to the status code of POST is 201, and other status codes are 200.

request object

The handler usually needs to access the request data sent by the client, and NestJs provides access to the request object of the underlying platform (Express by default), and we can use the decorator to obtain the object when we want to use it @Req. The specific code is as follows:

@Get()
getCommodityList(@Req() request: Request): string {
    
    
  return '获取商品列表'
}

Note: In the above code, we used the Request object, and this object has no declaration for this object in NestJS, so we need to install @types/express.

There is a lot of information in the Request object, such as the HTTP header, body, parameters, etc. of the request. In most cases, we don't need to manually obtain these attributes, because NestJS has written the corresponding decorators for us. The specific decorators are as follows:

decorator Corresponding objects and properties
@Request(), @Req() request object
@Response(), @Res()* response object
@Next() next object
@Session() The session attribute in the request object
@Param(key?: string) The params object in the request object
@Body(key?: string) The body object of the request object
@Query(key?: string) The query object in the request object
@Headers(name?: string) The headers object in the request object
@Ip() IP information attribute in request object
@HostParam() The host information attribute in the request object

Note: In NestJs, the program response processing has already done it for us. We just need to return the data directly without any special processing. If you inject @Req() or @Response() in the method, you can It is equivalent to putting Nest in a special platform mode, so that the response needs to be processed by yourself, that is, the response must be sent by calling the object response (res.json() or res.send()), otherwise the HTTP server will will hang.

route wildcard

Decorators for standard HTTP methods are provided in NestJs: @Get(), @Post(), @Put(), @Delete(), @Patch(), @Options()and @Head().

The characters ?, +, *, and () in routing wildcards are subsets of their regular expression counterparts.

Specific examples of wildcards are as follows:

// 匹配/random.text的请求路径
@Get('/random.text')
getTextInfo() {
    
    
  return '获取text文件'
}

// 匹配geinfo和getinfo的请求路径,即t字符允许出现一次或没有
@Get('/get?info')
getInfo() {
    
    
  return '?通配符'
}

// 匹配getabc或者gettabc的请求路径,即t字符最少出现一次和出现多次
@Get('/get+abc')
getAbc() {
    
    
  return '+通配符'
}

// 匹配/abe 和 /abcde
@Get('/ab(cd)?e')
getAbcd() {
    
    
  return '()通配符'
}

// 匹配以get开头的所有请求路径
@Get('/get*')
getCommodityList(@Req() request: Request): string {
    
    
  return '*通配符'
}

*The matching depth of wildcards is the largest among wildcards , so *it is best to put them last when using wildcards, because routing is matched from top to bottom in NestJs.

status code

As mentioned earlier, the response status code is always 200 by default, except for POST requests, which are 201. In NestJS we can use @HttpCode()decorators to set status codes.

set response header

In NestJs, if we want to customize the response header, we can use @Header()the decorator or use the response object to set it. The specific code is as follows:

@Put()
@Header('Cache-Control', 'none')
updateCommodity(): string {
    
     return '修改商品' }

redirect

In NestJs, we can use @Redirect()decorators to redirect to specific URLs. We can also use the response object to implement redirection.

The @Redirect()decorator can accept two parameters, one is the redirected URL, and the other is the status code of the response.

Sometimes the address we redirect is dynamically redirected after judging according to some parameters, as long as we do this.

@Get('search')
@Redirect('https://biyinig.com', 302)
getSearch(@Query('searchType') version: string) {
    
    
  if (version && version === 'baidu') {
    
    
    return {
    
     url: 'https://www.baidu.com' };
  }
}

Subdomain routing (authentication required)

@ControllerIn addition to accepting specified routes as parameters, the decorator can also receive hostobjects to declare other host addresses as real request addresses. Specific examples are as follows:

@Controller({
    
     host: "admin.example.com" })
export class AdminController {
    
    
  @Get()
  index(): string {
    
    
    return "Admin page";
  }
}

up and running

When we declare the controller, NestJs still doesn't know that the CatsController of the controller exists, so it won't create an instance of this class.

So we can AppModuleadd the controller we declared in. The specific code is as follows:

import {
    
     CommodityController } from "./controller/commodity.controller";
import {
    
     Module } from "@nestjs/common";
import {
    
     AppController } from "./app.controller";
import {
    
     AppService } from "./app.service";

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

After completing the above controller injection, we will create the corresponding controller instance when we start the program, so that we can access the corresponding interface.

おすすめ

転載: blog.csdn.net/qq_33003143/article/details/131886706