当前位置:网站首页>Configuration and use of controllers and routes in nestjs
Configuration and use of controllers and routes in nestjs
2022-06-30 05:06:00 【Johnny, me】
About Nest controller
1 ) The function of the controller
- Nest The controller layer in is responsible for handling incoming requests , And return the response to the client
- The purpose of the controller is to receive application specific requests . The routing mechanism controls which controller receives which requests
- Usually , Each controller has multiple routes , Different routes can perform different operations
2 ) The creation of the controller
- be based on cli Create the controller : $
nest g controller about - One controller corresponds to one class class , And usually use @Controller To decorate
Example :
import {
Controller } from '@nestjs/common';
@Controller('about')
export class AboutController {
}
- After executing the create command , Not only does it generate a src/about Catalog , Directory is 2 Controller files
- Namely :about.controller.spec.ts and about.controller.ts
- The main module has also been updated :/src/app.module.ts, That is, the controller module is automatically injected
- We continue to write business logic
Example :
import {
Controller, Get } from '@nestjs/common';
@Controller('about')
export class AboutController {
// about
@Get()
index():string {
// Notice the top index You can name it as you like , Not necessarily index
return ' I am a about page ';
}
// Notice in the decorator , Do not use semicolons ;
// /about/more
@Get("more")
getMore():string {
// Notice the top index You can name it as you like , Not necessarily index
return ' I am a about More pages for ';
}
}
- When the request handler returns JavaScript Object or array , It will be automatically serialized to JSON
- however , When it returns a string ,Nest Instead of serializing it, just send a string
- This makes response processing simple : Just return the value ,Nest Take care of the rest
3 ) Creation of other modules
- $
nest g --helpYou can view which modules can be created
About Nest route
1 ) summary
- Routing is another name for interface address , And routing and controller are inseparable
- The controller is used to respond to routing requests , In writing , We usually code based on decorator patterns
2 ) The function of ornaments
- The extension class , Method , attribute , And the function of parameters
- Provided by default :HTTP Decorator of the request method @Put() 、@Delete()、@Patch()、 @Options()、 @Head() and @All()
- It's very good RESTful Supported , Again , For request parameters , There are also some built-in decorators
@Request() req
@Response() res
@Next() next
@Session() req.session
@Param(key?: string) req.params / req.params[key]
@Body(key?: string) req.body / req.body[key]
@Query(key?: string) req.query / req.query[key]
@Headers(name?: string) req.headers / req.headers[name]
3 ) Examples of decorators
import {
Controller, Get, Post, Query, Request, Body } from '@nest/common';
@controller('cart')
export class CartController {
@Get()
index() {
return 'Shopping Cart';
}
@Get('add')
addCart(@Query() query) {
console.log(query);
return 'Add To Cart';
}
@Get('edit')
editCart(@Request() req) {
console.log(req.query);
return req.query;
}
@Post('create')
create(@Body body) {
console.log(body);
return 'create'
}
}
3 ) Configuration of dynamic routing
import {
Controller, Get, Post, Param, Query } from '@nest/common';
@controller('order')
export class OrderController {
@Post('add')
addOrder(@Query('id') id) {
// order/add?id=123
console.log('id: ', id)
return id;
}
@Get(':id')
index(@Param() param) {
// order/123
console.log(param);
return ' Current page parameters '
}
}
- Be careful , If the routing form is roughly the same , You need to pay attention to the search order , such as
- order/123 and order/add These two kinds of , Need to put add Put it on top , Avoid mismatches
4 ) Fuzzy matching of dynamic routing
import {
Controller, Get, Post, Param, Query } from '@nest/common';
@controller('order')
export class OrderController {
@Get('xx*yy')
vagueMatch() {
console.log('vague match');
return ' Fuzzy matching ';
}
@Post('add')
addOrder(@Query('id') id) {
// order/add?id=123
console.log('id: ', id)
return id;
}
@Get(':id')
index(@Param() param) {
// order/123
console.log(param);
return ' Current page parameters '
}
}
- It is also necessary to pay attention to the sequence
边栏推荐
- Golan no tests were run: fmt Printf() < BUG>
- Spring Festival Tourism Strategy: welcome the new year in Bangkok, Thailand
- Tensorflow2 of ubantu18.04 X installation
- 很紧张,第一天做软件测试,需要做什么?
- Chapter 10 of OpenGL super classic (7th Edition) calculation shader
- Unity multiple UI page turning left and right
- Using the command line to convert JSON to dart file in fluent
- 0 basic unity course. Bricklaying
- 003-JS-DOM-Attr-innerText
- Steamvr causes abnormal scene camera
猜你喜欢

Generate a slice of mesh Foundation

Sailing experience not to be missed in New York Tourism: take you to enjoy the magnificent city scenery from different perspectives

Force buckle 209 Minimum length subarray

Force buckle 704 Binary search

【VCS+Verdi联合仿真】~ 以计数器为例

Some books you should not miss when you are new to the workplace

UE4 method of embedding web pages

Preorder traversal of Li Kou 589:n fork tree

Unity packaging failure solution

On mask culling of unity
随机推荐
Unity3d packaging and publishing APK process
The difference between SVG and canvas
Unity camera control
Some problems encountered in unity steamvr
[vcs+verdi joint simulation] ~ take the counter as an example
PS1 Contemporary Art Center, Museum of modern art, New York
Chapter 7 vertex processing and drawing commands of OpenGL super classic (7th Edition)
力扣704. 二分查找
Unity + hololens common basic functions
MySQL query gadget (I) replace a property value of the object in the JSON array in the JSON format string field
力扣周赛293题解
Yolov5 torch installation
Special folders in unity3d and their meanings
003-JS-DOM-Attr-innerText
What is multimodal interaction?
Records of some problems encountered during unity development (continuously updated)
Unity + hololens publishing settings
一条命令运行rancher
JPA复合主键使用
Detailed explanation of the process of "flyingbird" small game (camera adjustment and following part)