当前位置:网站首页>Nest. JS uses express but not completely
Nest. JS uses express but not completely
2022-07-26 00:18:00 【Ink fragrance^_^】
Node.js Provides http The module is used to listen to the port 、 Handle http request , Return response , This is also the main thing it does .
however http Modular api Too primitive , It's cumbersome to process the request response directly based on it , So we will use express Wait for the library to encapsulate a layer .
What this layer does is give request and response Added a lot of methods to handle request responses , Meet the needs of various scenarios , And the routing is processed , and , The call chain of middleware is also provided to facilitate the reuse of some code , The call chain of this middleware is called the onion model .

But this layer does not solve the architecture problem : What to do when there are more modules , How to manage ? How to divide Model、View、Controller? wait .
therefore , use Node.js When doing back-end services, we will pack another layer , Solve architecture problems , The framework of this layer is eggjs( Ant's )、midwayjs( Taobao's )、nestjs( foreign ).
nestjs Is one of the best :


![]()
The bottom of this floor is still express、koa etc. , It's just in those http Based on the framework, the architecture problem is solved additionally .
and nestjs There's another thing I did very well , It doesn't depend on any one http platform , It can switch flexibly .
that nestjs How to switch to the underlying platform ?
Think react How to make vdom Render to canvas、dom、native Of ?
Define a unified interface , Of various platforms render Logic implements these interfaces . This pattern is called adapter pattern .
The adapter pattern is when a function implemented by a third party is used , Don't rely directly on , Instead, define a layer interface , Let the third party adapt to this layer interface . In this way, any scheme adapted to this layer interface can be integrated , It can also provide flexible switching schemes .
Nest.js To the bottom http The platform provides a layer interface (HttpServer), Defines a bunch of methods used :
![]()
because ts Of interface All methods must be implemented , In order to simplify the , It inherits another layer of abstract classes AbstractHttpAdapter, Define the method to be implemented as abstract Of .

then express Or other platforms, such as fastify Just inherit the class of this adapter , To implement the abstract methods , You can access Nest.js in :
such as ExpressAdapter:

perhaps FastifyAdapter:
![]()
These logic are placed in platform-express and platform-fastify In the bag :

Nest.js The first line of code calls create:

create You will choose one httpAdapter To create a service :

The default is express:

such , Subsequent calls request and response In the end, all the methods are express Of course. .
For example controller It can be used in @Request Decorator to inject reqeust object , You can call reqeust Various methods of .
import { Controller, Get, Request } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(@@Request() request: Request): string {
return 'This action returns all cats';
}
}If you want to call some platform specific methods outside the interface ,Nest.js Also support , Then switch to @Req To infuse :
import { Controller, Get, Req } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(@@Req() request: Request): string {
return 'This action returns all cats';
}
}What is injected in this way is a specific platform, such as express The native request object , You can use all its methods directly .
Besides , If you really want to use Express Platform specific api Words , stay NestFactory.create You can specify the corresponding type parameters when , In this way, you can do the corresponding type prompt and check :
![]()
But this is coupled to a specific platform , Unless you're sure you won't switch platforms , Otherwise, it's not recommended .
http The platform does this , Empathy ,websocket So is the platform :
A unified interface is defined , Connect to... Respectively through adapter socketio and websocket, It can switch flexibly :
![]()
Graphic below Nest.js About http 、websocket Platform handling :
![]()
summary
Node.js Provides http The module is used to listen to the port 、 Processing request response , But it's api Too primitive , So we'll wrap it up , stay express This layer provides more easy to use request、response Of api, But this layer doesn't solve the architecture problem , To introduce MVC、IOC And so on , It needs another layer , use Egg.js、Midway.js、Nest.js This higher-level back-end framework , among Nest.js Is the best .
Nest.js At the bottom and http Special design has been made on the integration of the platform , Using adapter mode , Provide a layer interface , Let the underlying platform adapt , In this way, you can flexibly switch between different http The platform .
But it also supports platform specific api, such as controller It can be used in @Req Injected into the underlying request object , When creating a container, you can also pass in the type parameters of the corresponding platform .
Nest.js The default is Express, But it didn't work Express Not exactly , Because you can flexibly switch between other . This is the charm of the adapter pattern .
边栏推荐
- Unity -- Euler angle, quaternion
- CyclicBarrier
- What does it mean that the web server stops responding?
- 如何让你的 JS 代码写得更漂亮
- Leetcode200 - find detailed explanation of the number of islands
- Detailed explanation of kubernetes network plug-ins - calico chapter - Overview
- 牛血清蛋白修饰酚酸类及生物碱类小分子/偶联微球的蛋白/牛红细胞SOD的研究
- FreeRTOS个人笔记-信号量
- Shib (firewood Dog Coin) rose hundreds of times in January. What core elements does a hundred times coin need? 2021-05-09
- Unity—欧拉角,四元数
猜你喜欢

Unity -- Euler angle, quaternion

Binary tree - 112. Path sum

letfaw

Duplicate disk: recommended system - negative sampling strategy

Js理解之路:Js常见的6中继承方式

06_ue4进阶_使用地形工具设置大地图

Elementary C language - branch statements (if, switch)

C language actual combat guessing game

Binary tree -- 222. Number of nodes of a complete binary tree

栈的表示和实现(C语言)
随机推荐
How does the server build a virtual host?
Getaverse,走向Web3的远方桥梁
"Animal coin" is fierce, trap or opportunity? 2021-05-12
本轮牛市还能持续多久?|疑问解答 2021-05-11
Leetcode shahutong series -- 63. Different paths II
FreeRTOS personal notes - message queue
Binary tree -- 257. All paths of binary tree
【Redis】① Redis 的介绍、Redis 的安装
MySQL - database log
Nodejs学习资源
MPLS中的包交换和标签交换
通货膨胀之下,后市如何操作?2021-05-14
Backtracking - 17. Letter combinations of phone numbers
没错,请求DNS服务器还可以使用UDP协议
LeetCode_ 55_ Jumping game
FreeRTOS personal notes - mutex
Js理解之路:什么是原型链
Instructions for pinduoduo's API to get the list of goods according to keywords
Prometheus operation and maintenance tool promtool (II) query function
寻找命令find和locate