当前位置:网站首页>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
边栏推荐
- [AI vision · quick review of NLP natural language processing papers today, issue 28] wed, 1 Dec 2021
- Overview of knowledge map (II)
- PolarMask is not in the models registry
- Counting and sorting (C language implementation) -- learning notes
- Common net HP UNIX system FTP server listfiles returns null solution.
- Websites frequented by old programmers (continuously updated)
- Xiaomi, qui a établi le plus grand volume de ventes de téléphones portables domestiques sur le marché d'outre - mer, se concentre de nouveau sur le marché intérieur
- Hard core chip removal
- [AI vision · quick review of today's sound acoustic papers issue 1] Thu, 14 APR 2022
- 創下國產手機在海外市場銷量最高紀錄的小米,重新關注國內市場
猜你喜欢
Xiaomi, qui a établi le plus grand volume de ventes de téléphones portables domestiques sur le marché d'outre - mer, se concentre de nouveau sur le marché intérieur
Abstract classes, interfaces and common keywords
Install PaddlePaddle on ARM
Xiaomi, which has set the highest sales record of domestic mobile phones in overseas markets, paid renewed attention to the domestic market
[AI vision · quick review of NLP natural language processing papers today, issue 30] Thu, 14 APR 2022
Notes sur l'apprentissage profond (Ⅱ) - - Principe et mise en oeuvre de la fonction d'activation
Hard core chip removal
On the principle of concurrent programming and the art of notify / Park
Source code and update details of new instance segmentation network panet (path aggregation network for instance segmentation)
MySQL is completely uninstalled and MySQL service is cleaned up
随机推荐
VSCode配置之Matlab极简配置
Detailed explanation on the use of annotation tool via (VGg image annotator) in mask RCNN
硬核拆芯片
Win10 boot VMware virtual machine boot seconds blue screen problem perfect solution
【BIM+GIS】ArcGIS Pro2.8如何打开Revit模型,BIM和GIS融合?
Identifier, keyword, data type
Second kill all interval related problems
【ICCV 2019】MAP-VAE:Multi-Angle Point Cloud-VAE: Unsupervised Feature Learning for 3D Point Clouds..
51 single chip microcomputer: D / a digital to analog conversion experiment
Xshell、Xftp连接新创建的Unbutu系统虚拟机全流程
Mysql出现2013 Lost connection to MySQL server during query
[string] ranking of country names ----- problem solving notes
Mechanical design knowledge point planning
Man's life
[AI vision · quick review of robot papers today, issue 30] Thu, 14 APR 2022
ROS series (I): rapid installation of ROS
一个函数秒杀2Sum 3Sum 4Sum问题
php导出Excel表格
Seekbar custom style details
UDP protocol and TCP protocol