当前位置:网站首页>Express middleware ① (use of Middleware)
Express middleware ① (use of Middleware)
2022-04-23 03:54:00 【Eighteen hates programming】
List of articles
- Express middleware
-
- What is Middleware
- Express Call process of Middleware
- Express Middleware format
- next Function function
- Define the simplest middleware function
- Globally effective middleware
- Define a simplified form of global middleware
- The role of middleware
- Define multiple global middleware
- Partially effective middleware
- Define multiple local middleware
- Learn about middleware 5 There are two points for attention
Express middleware
What is Middleware
middleware (Middleware)
, It refers to the intermediate process of business process .
We can give an example in life to better understand it :
When dealing with sewage , Generally Three processing links , So as to ensure that the treated wastewater , Meet the emission standard .
These three intermediate treatment links of sewage treatment , It can be called middleware .
Be careful : Middleware must have input and output
Express Call process of Middleware
When a request arrives Express After the server of , Multiple middleware can be called continuously , To preprocess this request .
Express Middleware format
Express Middleware , It's essentially one function Processing function ,Express The format of middleware is as follows :
Be careful : In the formal parameter list of middleware functions , Must contain next Parameters . The routing processing function only contains req and res.( We can use this to distinguish Middleware function
and Routing functions
)
next Function function
next Function is the key to realize the continuous call of multiple middleware , It means transferring the flow relationship to the next middleware or routing .
Called next The function represents that the middleware has finished processing , It's up to the next middleware or router to handle it
Define the simplest middleware function
It can be done by , Define the simplest middleware function :
Globally effective middleware
Any request from the client , After arriving at the server , Will trigger middleware , It's called globally effective middleware .
By calling app.use( Middleware function ), You can define a middleware that works globally , The sample code is as follows :
const express = require('express')
const app = express()
// Define the simplest middleware function
const mw = function (req, res, next) {
console.log(' This is the simplest middleware function ')
// Put the circulation relationship , Forward to the next middleware or route
next()
}
// take mw Register as a globally effective middleware
app.use(mw)
app.get('/', (req, res) => {
console.log(' Called / This route ')
res.send('Home page.')
})
app.get('/user', (req, res) => {
console.log(' Called /user This route ')
res.send('User page.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
Before we send to the server ’/user’GET After the request , We will get :
Define a simplified form of global middleware
We divided the definition and registration of middleware into two steps , Now we can synthesize them into one step to achieve the effect of simplification :
The code above can be changed to :
const express = require('express')
const app = express()
// This is a simplified form of defining global middleware
app.use((req, res, next) => {
console.log(' This is the simplest middleware function ')
next()
})
app.get('/', (req, res) => {
console.log(' Called / This route ')
res.send('Home page.')
})
app.get('/user', (req, res) => {
console.log(' Called /user This route ')
res.send('User page.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
The role of middleware
Between multiple middleware , Share the same req and res. Based on this characteristic , We can in the upstream middleware , Uniform for req or res Object to add custom properties or methods , For downstream middleware or routing .
For example, now we define a requirement : We need to get the time when the request arrives at the server
If we don't use middleware , We need to make a single acquisition in each route , This is undoubtedly very troublesome .
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')
})
Middleware will be much easier to use :
const express = require('express')
const app = express()
// This is a simplified form of defining global middleware
app.use((req, res, next) => {
// Get the time when the request arrived at the server
const time = Date.now()
// by req object , Mount custom properties , So that we can share the time with all the other routes
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')
})
Define multiple global middleware
have access to app.use() Continuously define multiple global middleware . After the client request arrives at the server , It will be called in the order defined by the middleware , The sample code is as follows :
const express = require('express')
const app = express()
// Define the first global middleware
app.use((req, res, next) => {
console.log(' Called the 1 A global middleware ')
next()
})
// Define the second global middleware
app.use((req, res, next) => {
console.log(' Called the 2 A global middleware ')
next()
})
// Define a route
app.get('/user', (req, res) => {
res.send('User page.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
When we are right ’/user’ send out GET After the request, we will get the following results ( Server side ):
Partially effective middleware
Don't use app.use() Defined middleware , Middleware called local validation , The sample code is as follows :
Define multiple local middleware
In routing , Through the following two equivalent ways , Use multiple local middleware :
Learn about middleware 5 There are two points for attention
① Be sure to register middleware before routing ( There are exceptions , Error level middleware )
② The request sent by the client , Multiple middleware can be called continuously for processing
③ After executing the business code of middleware , Don't forget to call next() function
④ In order to prevent code logic confusion , call next() Don't write extra code after the function
⑤ When calling multiple Middleware in succession , Between multiple middleware , share req and res object
版权声明
本文为[Eighteen hates programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230353066661.html
边栏推荐
- Instructions for fastmock
- MySQL is completely uninstalled and MySQL service is cleaned up
- [Li Hongyi 2022 machine learning spring] hw6_ Gan (don't understand...)
- ROS series (IV): ROS communication mechanism series (2): Service Communication
- 将编译安装的mysql加入PATH环境变量
- Mechanical design knowledge point planning
- php导出Excel表格
- Vs Studio modifie le langage C scanf et d'autres erreurs
- Win10 boot VMware virtual machine boot seconds blue screen problem perfect solution
- 秒杀所有区间相关问题
猜你喜欢
[AI vision · quick review of NLP natural language processing papers today, issue 28] wed, 1 Dec 2021
ROS series (IV): ROS communication mechanism series (5): Service Communication Practice
ROS series (4): ROS communication mechanism series (4): topic communication practice
A function second kill 2sum 3sum 4sum problem
Idea debug debugging tutorial
Identifier, keyword, data type
Detailed explanation on the use of annotation tool via (VGg image annotator) in mask RCNN
Install PaddlePaddle on ARM
Variables, constants, operators
Common auxiliary classes
随机推荐
MySQL zip installation tutorial
对象和类的概念
Idea debug debugging tutorial
Nel ASA: her ø Ya facility in Norway officially opened
Key point detection of human hand based on mediapipe
SQL learning record
【NeurIPS 2019】Self-Supervised Deep Learning on Point Clouds by Reconstructing Space
Use of rotary selector wheelpicker
Basic knowledge of convolutional neural network
Express中间件①(中间件的使用)
Jupiter notebook modify configuration file setting startup directory is invalid
[AI vision · quick review of robot papers today, issue 30] Thu, 14 APR 2022
CRF based medical entity recognition baseline
使用大华设备开发行AI人流量统计出现时间不正确的原因分析
What is software acceptance testing? What are the benefits of acceptance testing conducted by third-party software testing institutions?
STM32 advanced timer com event
2021-09-03 crawler template (only static pages are supported)
[latex] differences in the way scores are written
一个函数秒杀2Sum 3Sum 4Sum问题
Cause analysis of incorrect time of AI traffic statistics of Dahua Equipment Development Bank