当前位置:网站首页>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
- Detailed explanation of constraints of Oracle table
- Information: 2021 / 9 / 29 10:01 - build completed with 1 error and 0 warnings in 11S 30ms error exception handling
- Zero copy technology
- Tensorflow & pytorch common error reporting
- AI21 Labs | Standing on the Shoulders of Giant Frozen Language Models(站在巨大的冷冻语言模型的肩膀上)
- What does the SQL name mean
- MySQL [read / write lock + table lock + row lock + mvcc]
- Tensorflow Download
- Tangent space
猜你喜欢
![[Video] Bayesian inference in linear regression and R language prediction of workers' wage data | data sharing](/img/12/a330b5e77921bbfa8e96fcbc660daa.png)
[Video] Bayesian inference in linear regression and R language prediction of workers' wage data | data sharing

Common types and basic usage of input plug-in of logstash data processing service

Usereducer basic usage

Cross carbon market and Web3 to achieve renewable transformation

TIA博途中基於高速計數器觸發中斷OB40實現定點加工動作的具體方法示例

Dolphin scheduler source package Src tar. GZ decompression problem

初探 Lambda Powertools TypeScript

SAP ui5 application development tutorial 72 - trial version of animation effect setting of SAP ui5 page routing

Lenovo Saver y9000x 2020

Information: 2021 / 9 / 29 10:01 - build completed with 1 error and 0 warnings in 11S 30ms error exception handling
随机推荐
SQL learning | set operation
Analysis of cluster component gpnp failed to start successfully in RAC environment
[code analysis (4)] communication efficient learning of deep networks from decentralized data
Cross carbon market and Web3 to achieve renewable transformation
Move blog to CSDN
Android 面试主题集合整理
leetcode--380.O(1) 时间插入、删除和获取随机元素
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
SQL learning window function
函数只执行第一次的执行一次 once函数
Using Jupiter notebook in virtual environment
OSS cloud storage management practice (polite experience)
QT calling external program
Express中间件③(自定义中间件)
Modification of table fields by Oracle
Error 403 in most cases, you or one of your dependencies are requesting
Solution: you have 18 unapplied migration (s) Your project may not work properly until you apply
Use of GDB
Oracle database combines the query result sets of multiple columns into one row
Basic SQL query and learning