当前位置:网站首页>Express middleware ③ (custom Middleware)
Express middleware ③ (custom Middleware)
2022-04-23 13:47:00 【Eighteen hates programming】
List of articles
Custom middleware
Manually simulate one by yourself, similar to express.urlencoded Such middleware , Parsing POST Form data submitted to the server .
The implementation steps are as follows :
① Define middleware
② monitor req Of data event
③ monitor req Of end event
④ Use querystring The module parses the request body data
⑤ Mount the parsed data object as req.body
⑥ Encapsulate the custom middleware into modules
Implementation steps
Define middleware
Use app.use() To define the middleware with global effect , The code is as follows :

monitor req Of data event
In the middleware , Need to monitor req Object's data event , To get the data sent by the client to the server .
If the amount of data is large , Cannot send all at once , Then the client will cut the data , Distributed to the server . therefore data Events can trigger multiple times ( Every time you send data , Will trigger once data event ), Every time it triggers data When an event is , Getting the data is only part of the complete data , The received data needs to be spliced manually .
as follows :

monitor req Of end event
When the request body data is received , Will automatically trigger req Of end event .
therefore , We can do it in req Of end Incident , Get and process the complete request body data . The sample code is as follows :

Use querystring The module parses the request body data
Node.js There's a built-in querystring modular , Specifically used to process query strings . Provided through this module parse() function , It's easy Put query string , Parse into object format . The sample code is as follows :

Mount the parsed data object as req.body
Between upstream middleware and downstream middleware and routing , Share the same req and res. therefore , We can parse the data , Mount as req Custom properties for , Name it req.body, For downstream use . The sample code is as follows :

Encapsulate the custom middleware into modules
In order to optimize the structure of the code , We can put custom middleware functions , Encapsulated as a separate module , The sample code is as follows :

Summarize the above steps , The code implementation is as follows :
Custom module section :
// Import Node.js Built in querystring modular
const qs = require('querystring')
const bodyParser = (req, res, next) => {
// Define the specific business logic of middleware
// 1. Define a str character string , It is specially used to store the request body data sent by the client
let str = ''
// 2. monitor req Of data event
req.on('data', (chunk) => {
str += chunk
})
// 3. monitor req Of end event
req.on('end', () => {
// stay str The complete request body data is stored in the
// console.log(str)
// TODO: Put the request body data in string format , Resolve to object format
const body = qs.parse(str)
req.body = body
next()
})
}
module.exports = bodyParser
The main program part :
// Import express modular
const express = require('express')
// establish express Server instance of
const app = express()
// 1. Import your own encapsulated middleware module
const customBodyParser = require('./14.custom-body-parser')
// 2. The customized middleware functions , Register as a globally available middleware
app.use(customBodyParser)
app.post('/user', (req, res) => {
res.send(req.body)
})
// 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/202204231337076695.html
边栏推荐
- Modification of table fields by Oracle
- Dolphin scheduler configuring dataX pit records
- Test the time required for Oracle library to create an index with 7 million data in a common way
- 19c environment ora-01035 login error handling
- 联想拯救者Y9000X 2020
- Influence of openssh version on SSH mutual trust creation in RAC environment
- Express②(路由)
- 低频量化之明日涨停预测
- Opening: identification of double pointer instrument panel
- ARGB transparency conversion
猜你喜欢

10g database cannot be started when using large memory host

Lenovo Saver y9000x 2020

Kettle--控件解析

2022年江西最新建筑八大员(质量员)模拟考试题库及答案解析

Tangent space

Tersus notes employee information 516 MySQL query (time period uniqueness judgment of 2 fields)

【报名】TF54:工程师成长地图与卓越研发组织打造

【项目】小帽外卖(八)

MySQL and PgSQL time related operations

Express②(路由)
随机推荐
MySQL [SQL performance analysis + SQL tuning]
AI21 Labs | Standing on the Shoulders of Giant Frozen Language Models(站在巨大的冷冻语言模型的肩膀上)
pycharm Install packages failed
Personal learning related
初探 Lambda Powertools TypeScript
Zero copy technology
软考系统集成项目管理工程师全真模拟题(含答案、解析)
Express ② (routage)
Storage scheme of video viewing records of users in station B
Core concepts of microservice architecture
Ai21 labs | standing on the shoulders of giant frozen language models
[machine learning] Note 4. KNN + cross validation
Oracle database combines the query result sets of multiple columns into one row
Interval query through rownum
Information: 2021 / 9 / 29 10:01 - build completed with 1 error and 0 warnings in 11S 30ms error exception handling
Oracle view related
Error 403 in most cases, you or one of your dependencies are requesting
Antd design form verification
Small case of web login (including verification code login)
Building MySQL environment under Ubuntu & getting to know SQL