当前位置:网站首页>Express中间件①(中间件的使用)
Express中间件①(中间件的使用)
2022-04-23 03:53:00 【十八岁讨厌编程】
文章目录
Express中间件
什么是中间件
中间件(Middleware)
,特指业务流程的中间处理环节。
我们可以举一个生活中的例子来更好的理解它:
在处理污水的时候,一般都要经过三个处理环节,从而保证处理过后的废水,达到排放标准。
处理污水的这三个中间处理环节,就可以叫做中间件。
注意:中间件是必须要有输入和输出的
Express 中间件的调用流程
当一个请求到达 Express 的服务器之后,可以连续调用多个中间件,从而对这次请求进行预处理。
Express 中间件的格式
Express 的中间件,本质上就是一个 function 处理函数,Express 中间件的格式如下:
注意:中间件函数的形参列表中,必须包含 next 参数。而路由处理函数中只包含 req 和 res。(我们可以利用这点来区别中间件函数
和路由处理函数
)
next 函数的作用
next 函数是实现多个中间件连续调用的关键,它表示把流转关系转交给下一个中间件或路由。
调用了next函数代表这个中间件处理完毕了,要交给下一个中间件或者路由去处理了
定义一个最简单的中间件函数
可以通过如下的方式,定义一个最简单的中间件函数:
全局生效的中间件
客户端发起的任何请求,到达服务器之后,都会触发的中间件,叫做全局生效的中间件。
通过调用 app.use(中间件函数),即可定义一个全局生效的中间件,示例代码如下:
const express = require('express')
const app = express()
// 定义一个最简单的中间件函数
const mw = function (req, res, next) {
console.log('这是最简单的中间件函数')
// 把流转关系,转交给下一个中间件或路由
next()
}
// 将 mw 注册为全局生效的中间件
app.use(mw)
app.get('/', (req, res) => {
console.log('调用了 / 这个路由')
res.send('Home page.')
})
app.get('/user', (req, res) => {
console.log('调用了 /user 这个路由')
res.send('User page.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
在我们向服务器发送’/user’GET请求后,我们将得到:
定义全局中间件的简化形式
我们前面是将中间件的定义与注册分成了两步,现在我们可以将它们合成一步来达到简化的效果:
我们上面的代码就可以改成:
const express = require('express')
const app = express()
// 这是定义全局中间件的简化形式
app.use((req, res, next) => {
console.log('这是最简单的中间件函数')
next()
})
app.get('/', (req, res) => {
console.log('调用了 / 这个路由')
res.send('Home page.')
})
app.get('/user', (req, res) => {
console.log('调用了 /user 这个路由')
res.send('User page.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
中间件的作用
多个中间件之间,共享同一份 req 和 res。基于这样的特性,我们可以在上游的中间件中,统一为 req 或 res 对象添加自定义的属性或方法,供下游的中间件或路由进行使用。
例如现在我们定义一种需求:我们需要获取请求到达服务器的时间
如果我们不使用中间件的话,我们就需要在每一个路由中都进行单个的获取,这无疑非常的麻烦。
const express = require('express')
const app = express()
app.get('/', (req, res) => {
const time = Date.now()
res.send('Home page.')
})
app.get('/user', (req, res) => {
const time = Date.now()
res.send('User page.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
如果使用中间件将简便许多:
const express = require('express')
const app = express()
// 这是定义全局中间件的简化形式
app.use((req, res, next) => {
// 获取到请求到达服务器的时间
const time = Date.now()
// 为 req 对象,挂载自定义属性,从而把时间共享给后面的所有路由
req.startTime = time
next()
})
app.get('/', (req, res) => {
res.send('Home page.' + req.startTime)
})
app.get('/user', (req, res) => {
res.send('User page.' + req.startTime)
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
定义多个全局中间件
可以使用 app.use() 连续定义多个全局中间件。客户端请求到达服务器之后,会按照中间件定义的先后顺序依次进行调用,示例代码如下:
const express = require('express')
const app = express()
// 定义第一个全局中间件
app.use((req, res, next) => {
console.log('调用了第1个全局中间件')
next()
})
// 定义第二个全局中间件
app.use((req, res, next) => {
console.log('调用了第2个全局中间件')
next()
})
// 定义一个路由
app.get('/user', (req, res) => {
res.send('User page.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
当我们对’/user’发送GET请求之后我们会得到如下的结果(服务器端):
局部生效的中间件
不使用 app.use() 定义的中间件,叫做局部生效的中间件,示例代码如下:
定义多个局部的中间件
可以在路由中,通过如下两种等价的方式,使用多个局部中间件:
了解中间件的5个使用注意事项
① 一定要在路由之前注册中间件(有例外,错误级别的中间件)
② 客户端发送过来的请求,可以连续调用多个中间件进行处理
③ 执行完中间件的业务代码之后,不要忘记调用 next() 函数
④ 为了防止代码逻辑混乱,调用 next() 函数后不要再写额外的代码
⑤ 连续调用多个中间件时,多个中间件之间,共享 req 和 res 对象
版权声明
本文为[十八岁讨厌编程]所创,转载请带上原文链接,感谢
https://blog.csdn.net/zyb18507175502/article/details/124353528
边栏推荐
- [AI vision · quick review of robot papers today, issue 28] wed, 1 Dec 2021
- [AI vision · quick review of NLP natural language processing papers today, issue 29] Mon, 14 Feb 2022
- Paddlepaddle model to onnx
- 作为一名码农,女友比自己更能码是一种什么体验?
- Design and implementation of redis (5): master-slave replication strategy and optimization
- MySQL zip installation tutorial
- Common exceptions
- The art of concurrent programming (6): explain the principle of reentrantlock in detail
- 【李宏毅2022 机器学习春】hw6_GAN(不懂..)
- Detailed explanation on the use of annotation tool via (VGg image annotator) in mask RCNN
猜你喜欢
Design and implementation of redis (6): how redis achieves high availability
OpenCV----YOLACT实例分割模型推理
一个函数秒杀2Sum 3Sum 4Sum问题
創下國產手機在海外市場銷量最高紀錄的小米,重新關注國內市場
Wechat applet cloud database value assignment to array error
Shopping mall for transportation tools based on PHP
SQL learning record
[AI vision · quick review of robot papers today, issue 30] Thu, 14 APR 2022
Seekbar custom style details
The whole process of connecting the newly created unbutu system virtual machine with xshell and xftp
随机推荐
Variables, constants, operators
What if win10 doesn't have a local group policy?
ROS series (IV): ROS communication mechanism series (5): Service Communication Practice
ROS series (IV): ROS communication mechanism series (3): parameter server
常用的辅助类
Why is it necessary to divide the variance by 255^2 when adding Gaussian noise using the imnoise function of MATLAB
[AI vision · quick review of NLP natural language processing papers today, issue 28] wed, 1 Dec 2021
A function second kill 2sum 3sum 4sum problem
ROS series (III): introduction to ROS architecture
将编译安装的mysql加入PATH环境变量
VS Studio 修改C語言scanf等報錯
Source code and update details of new instance segmentation network panet (path aggregation network for instance segmentation)
Vscode download and installation + running C language
Add the compiled and installed Mysql to the path environment variable
AI CC 2019 installation tutorial under win10 (super detailed - small white version)
Several common methods of multithreading
ROS series (II): ROS quick experience, taking HelloWorld program as an example
Vs Studio modifie le langage C scanf et d'autres erreurs
Nel ASA:挪威Herøya设施正式启用
RuntimeError: output with shape [4, 1, 512, 512] doesn‘t match the broadcast shape[4, 4, 512, 512]