当前位置:网站首页>Express middleware ② (classification of Middleware)
Express middleware ② (classification of Middleware)
2022-04-23 03:54:00 【Eighteen hates programming】
List of articles
Classification of middleware
In order to facilitate our understanding and memory of the use of middleware ,Express The official use of common middleware , Divided into 5 Categories: , Namely :
① Application level middleware
② Routing level middleware
③ Error level middleware
④ Express Built-in middleware
⑤ Third party middleware
Application level middleware
adopt app.use() or app.get() or app.post() , Bound to the app Middleware on instance , It's called application level middleware , The code example is as follows :
Routing level middleware
Bound to the express.Router() Middleware on instance , It's called routing level middleware . There is no difference between its usage and application level middleware . It's just , Application level middleware is bound to app For instance , The routing level middleware is bound to router For instance , The code example is as follows :
Error level middleware
The role of error level middleware : It's designed to catch unexpected errors in the entire project , So as to prevent the abnormal collapse of the project .
Format : Error level middleware function In the processing function , There has to be 4 Parameters , The order of formal parameters is from front to back , Namely (err, req, res, next).
Be careful : Error level middleware , Must register after all routes !
Because in the order from front to back , If you put the error level Middleware in front , When an error occurs , There is no processing code when the program is executed later .
Express Built-in middleware
since Express 4.16.0 Version start ,Express Built in 3 A common middleware , Greatly improved Express Project development efficiency and experience :
① express.static Built in middleware for fast hosting static resources , for example : HTML file 、 picture 、CSS Patterns, etc ( No compatibility )
② express.json analysis JSON Request body data in format ( Compatibility , Only in 4.16.0+ Available in version )
③ express.urlencoded analysis URL-encoded Request body data in format ( Compatibility , Only in 4.16.0+ Available in version )
Examples of use :
express.json Use example of
// Import express modular
const express = require('express')
// establish express Server instance of
const app = express()
// Be careful : Except for error level middleware , Other middleware , Must be configured before routing
// adopt express.json() This middleware , Parse... In the form JSON Formatted data
app.use(express.json())
app.post('/user', (req, res) => {
// On the server , have access to req.body This attribute , To receive the request body data sent by the client
// By default , If you don't configure middleware to parse form data , be req.body Default equal to undefined
console.log(req.body)
res.send('ok')
})
// call app.listen Method , Specify the port number and start web The server
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
Be careful : On the server side , Can pass req,body To get JSON Form data and url-encoded Formatted data
By default , If you don't configure middleware to parse form data , be req.body Default equal to undefined
express.urlencoded Examples of use
// Import express modular
const express = require('express')
// establish express Server instance of
const app = express()
// Be careful : Except for error level middleware , Other middleware , Must be configured before routing
// adopt express.urlencoded() This middleware , Parsing In the form url-encoded Formatted data
app.use(express.urlencoded({
extended: false }))
app.post('/book', (req, res) => {
// On the server , have access to req.body This attribute , To receive the request body data sent by the client
// By default , If you don't configure middleware to parse form data , be req.body Default equal to undefined
// On the server side , Can pass req,body To get JSON Form data and url-encoded Formatted data
console.log(req.body)
res.send('ok')
})
// call app.listen Method , Specify the port number and start web The server
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
Third party middleware
Not Express The official built-in , It's middleware developed by a third party , It's called third-party middleware . In the project , You can download and configure third-party middleware as needed , So as to improve the development efficiency of the project .
for example : stay [email protected] In the previous version , Regular use body-parser This third-party middleware , To parse the request body data . The procedure is as follows :
- function npm install body-parser Install middleware
- Use require Import Middleware
- call app.use() Register and use middleware
Be careful :Express Built in express.urlencoded middleware , Is based on body-parser This third-party middleware is further encapsulated .
( This explains why the registration syntax of the two is so similar )
Use the code :
// Import express modular
const express = require('express')
// establish express Server instance of
const app = express()
// 1. Import middleware for parsing form data body-parser
const parser = require('body-parser')
// 2. Use app.use() Register middleware
app.use(parser.urlencoded({
extended: false }))
// app.use(express.urlencoded({ extended: false }))
app.post('/user', (req, res) => {
// If there is no middleware configured to parse form data , be req.body Default equal to undefined
console.log(req.body)
res.send('ok')
})
// call app.listen Method , Specify the port number and start web The server
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
版权声明
本文为[Eighteen hates programming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230353066610.html
边栏推荐
- Vs studio modifies C language scanf and other errors
- 现货黄金操作技巧_估波曲线
- Add the compiled and installed Mysql to the path environment variable
- Identificateur, mot - clé, type de données
- Leetcode 617 merge binary tree
- Hard core chip removal
- Instructions for fastmock
- CRF based medical entity recognition baseline
- Wechat payment iframe sub page has no response
- 列表、元组、字典和集合的区别
猜你喜欢
标识符、关键字、数据类型
STM32 advanced timer com event
Seekbar custom style details
作为一名码农,女友比自己更能码是一种什么体验?
A sword is a sword. There is no difference between a wooden sword and a copper sword
How Zotero quotes in word jump to references / hyperlink
Set经典小题目
Network principle | connection management mechanism in TCP / IP important protocol and core mechanism
Second kill all interval related problems
对象和类的概念
随机推荐
Who will answer the question?
MySQL zip installation tutorial
Instructions for fastmock
Using VBA interval to extract one column from another in Excel
Install PaddlePaddle on ARM
QT program integration easyplayer RTSP streaming media player screen flicker what is the reason?
The super large image labels in remote sensing data set are cut into specified sizes and saved into coco data set - target detection
vscode删除卸载残余
[AI vision · quick review of today's sound acoustic papers issue 1] Thu, 14 APR 2022
AI CC 2019 installation tutorial under win10 (super detailed - small white version)
Leetcode 617 merge binary tree
Seekbar custom style details
Variables, constants, operators
Source code and update details of new instance segmentation network panet (path aggregation network for instance segmentation)
SQL topic exercise summary
Photoshop installation under win10
Installation and configuration of MinGW under win10
Common auxiliary classes
[AI vision · quick review of NLP natural language processing papers today, issue 30] Thu, 14 APR 2022
Openvino only supports Intel CPUs of generation 6 and above