当前位置:网站首页>Nestjs中控制器和路由的配置使用
Nestjs中控制器和路由的配置使用
2022-06-30 05:01:00 【Johnny丶me】
关于Nest控制器
1 ) 控制器的作用
- Nest中的控制器层负责处理传入的请求, 并返回对客户端的响应
- 控制器的目的是接收应用的特定请求。路由机制控制哪个控制器接收哪些请求
- 通常,每个控制器有多个路由,不同的路由可以执行不同的操作
2 ) 控制器的创建
- 基于cli对控制器进行创建: $
nest g controller about - 一个控制器就对应一个class类, 并且通常会使用@Controller的装饰器来装饰
示例:
import {
Controller } from '@nestjs/common';
@Controller('about')
export class AboutController {
}
- 当执行创建命令后,不仅生成了一个src/about目录,目录下有2个控制器文件
- 分别是:about.controller.spec.ts 和 about.controller.ts
- 还更新了主模块:/src/app.module.ts, 也就是自动注入了该控制器模块
- 我们继续写业务逻辑
示例:
import {
Controller, Get } from '@nestjs/common';
@Controller('about')
export class AboutController {
// about
@Get()
index():string {
// 注意上面的index可以随意命名,不一定要用index
return '我是about页面';
}
// 注意在装饰器中,不要使用分号;
// /about/more
@Get("more")
getMore():string {
// 注意上面的index可以随意命名,不一定要用index
return '我是about的更多页面';
}
}
- 当请求处理程序返回JavaScript对象或数组时,它将自动序列化为JSON
- 但是,当它返回一个字符串时,Nest 将只发送一个字符串而不是序列化它
- 这使响应处理变得简单:只需要返回值,Nest 负责其余部分
3 )其他模块的创建
- $
nest g --help可查看哪些模块可以创建
关于Nest路由
1 ) 概述
- 路由就是接口地址的另一种称谓,而且路由和控制器密不可分
- 控制器用于响应路由请求,在写法上,我们通常会基于装饰器模式编码
2 )装饰器的作用
- 扩展类,方法,属性,以及参数的功能
- 默认提供:HTTP 请求方法的装饰器 @Put() 、@Delete()、@Patch()、 @Options()、 @Head()和 @All()
- 很好的对RESTful进行了支持,同样,对请求参数,也提供了一些内置装饰器
@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 ) 装饰器示例
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 ) 动态路由的配置
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 '当前页面参数'
}
}
- 注意,如果路由形式大体相同,需要注意查找顺序,比如
- order/123 和 order/add 这两种,需要将add放入上面,避免匹配不到
4 ) 动态路由的模糊匹配
import {
Controller, Get, Post, Param, Query } from '@nest/common';
@controller('order')
export class OrderController {
@Get('xx*yy')
vagueMatch() {
console.log('vague match');
return '模糊匹配';
}
@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 '当前页面参数'
}
}
- 同样需要注意顺序问题
边栏推荐
- Create a simple battle game with photon pun
- Create transfer generation point
- Redis cluster concept
- Free travel recommendation in Bangkok: introduction to the Mekong River in Bangkok
- 力扣292周赛题解
- Unreal 4 learning notes - data storage using blueprints
- Universal Studios Singapore: a good place for a one-day parent-child tour in Singapore
- JPA复合主键使用
- Unit screenshot saved on the phone
- Singapore parent-child tour, these popular attractions must be arranged
猜你喜欢

EasyRecovery数据恢复软件 恢复了我两年前的照片视频数据

Singapore must visit these scenic spots during the Spring Festival

Deep learning ----- different methods to realize inception-10

Li Kou 2049: count the number of nodes with the highest score

Efficiency test of adding and querying ArrayList and LinkedList

Photon pun refresh hall room list

Yolov5 torch installation

Detailed explanation of the process of "flyingbird" small game (camera adjustment and following part)

Collective system

Meet in Bangkok for a romantic trip on Valentine's Day
随机推荐
Introduction to some representations, neighbors and degrees of Graphs
2021-07-29 compilation of Cura in ubantu18.04
Unity is associated with vs. there is a compiler problem when opening
Unity notes_ SQL Function
ParticleSystem in the official Manual of unity_ Collision module
Check London attractions suitable for parents and children in winter vacation
Thread safety and processing caused by multithreading
Error about the new version of UE4: unavigationsystemv1:: simplemovetoactor has been deprecated
Have a heart beating Valentine's day in Singapore
Preorder traversal of Li Kou 589:n fork tree
Steamvr causes abnormal scene camera
Important knowledge points in unity3d
Efficiency test of adding and querying ArrayList and LinkedList
Exploration of unity webgl
【Paper】2021_ Observer-Based Controllers for Incrementally Quadratic Nonlinear Systems With Disturbanc
Some problems encountered in unity steamvr
The difference between SVG and canvas
Unity multiple UI page turning left and right
【Paper】2019_ Consensus Control of Multiple AUVs Recovery System Under Switching Topologies and Time D
Writing unityshader with sublimetext