当前位置:网站首页>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
边栏推荐
- Troubleshooting of expdp export error when Oracle table has logical bad blocks
- Special window function rank, deny_ rank, row_ number
- The query did not generate a result set exception resolution when the dolphin scheduler schedules the SQL task to create a table
- sys. dbms_ scheduler. create_ Job creates scheduled tasks (more powerful and rich functions)
- Oracle generates millisecond timestamps
- The difference between is and as in Oracle stored procedure
- Express②(路由)
- OSS cloud storage management practice (polite experience)
- Handling of high usage of Oracle undo
- 软考系统集成项目管理工程师全真模拟题(含答案、解析)
猜你喜欢
Lenovo Savior y9000x 2020
Leetcode brush question 897 incremental sequential search tree
Why do you need to learn container technology to engage in cloud native development
切线空间(tangent space)
AI21 Labs | Standing on the Shoulders of Giant Frozen Language Models(站在巨大的冷冻语言模型的肩膀上)
Search ideas and cases of large amount of Oracle redo log
Campus takeout system - "nongzhibang" wechat native cloud development applet
Ai21 labs | standing on the shoulders of giant frozen language models
Solution of discarding evaluate function in surprise Library
SQL learning | set operation
随机推荐
Cross carbon market and Web3 to achieve renewable transformation
Modification of table fields by Oracle
解决方案架构师的小锦囊 - 架构图的 5 种类型
MySQL index [data structure + index creation principle]
【视频】线性回归中的贝叶斯推断与R语言预测工人工资数据|数据分享
Reading notes: Secure federated matrix factorization
Window function row commonly used for fusion and de duplication_ number
Move blog to CSDN
Lenovo Saver y9000x 2020
leetcode--977. Squares of a Sorted Array
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
[code analysis (4)] communication efficient learning of deep networks from decentralized data
联想拯救者Y9000X 2020
[code analysis (1)] communication efficient learning of deep networks from decentralized data
切线空间(tangent space)
About me
Analysis of redo log generated by select command
SQL learning | complex query
[code analysis (3)] communication efficient learning of deep networks from decentralized data
Ai21 labs | standing on the shoulders of giant frozen language models