当前位置:网站首页>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
边栏推荐
- [code analysis (2)] communication efficient learning of deep networks from decentralized data
- Operations related to Oracle partition
- Solution: you have 18 unapplied migration (s) Your project may not work properly until you apply
- 解决tp6下载报错Could not find package topthink/think with stability stable.
- Common types and basic usage of input plug-in of logstash data processing service
- [code analysis (6)] communication efficient learning of deep networks from decentralized data
- Oracle clear SQL cache
- Kettle--控件解析
- 【项目】小帽外卖(八)
- Express ② (routage)
猜你喜欢
Express中间件③(自定义中间件)
Oracle defines self incrementing primary keys through triggers and sequences, and sets a scheduled task to insert a piece of data into the target table every second
The query did not generate a result set exception resolution when the dolphin scheduler schedules the SQL task to create a table
MySQL index [data structure + index creation principle]
Special window function rank, deny_ rank, row_ number
SAP ui5 application development tutorial 72 - animation effect setting of SAP ui5 page routing
The interviewer dug a hole for me: how many concurrent TCP connections can a single server have?
SQL learning | complex query
Modify the Jupiter notebook style
Express ② (routage)
随机推荐
Two ways to deal with conflicting data in MySQL and PG Libraries
Zero copy technology
PG library to view the distribution keys of a table in a certain mode
Oracle job scheduled task usage details
What does the SQL name mean
MySQL and PgSQL time related operations
SQL learning | complex query
Antd design form verification
Troubleshooting of expdp export error when Oracle table has logical bad blocks
Oracle lock table query and unlocking method
Building MySQL environment under Ubuntu & getting to know SQL
自动化的艺术
初探 Lambda Powertools TypeScript
Storage scheme of video viewing records of users in station B
Use of GDB
Analysis of redo log generated by select command
[machine learning] Note 4. KNN + cross validation
Reading notes: Secure federated matrix factorization
Basic SQL query and learning
2022年江西最新建筑八大员(质量员)模拟考试题库及答案解析