当前位置:网站首页>Express中间件③(自定义中间件)
Express中间件③(自定义中间件)
2022-04-23 13:37:00 【十八岁讨厌编程】
文章目录
自定义中间件
自己手动模拟一个类似于 express.urlencoded 这样的中间件,来解析 POST 提交到服务器的表单数据。
实现步骤如下:
① 定义中间件
② 监听 req 的 data 事件
③ 监听 req 的 end 事件
④ 使用 querystring 模块解析请求体数据
⑤ 将解析出来的数据对象挂载为 req.body
⑥ 将自定义中间件封装为模块
实现步骤
定义中间件
使用 app.use() 来定义全局生效的中间件,代码如下:
监听 req 的 data 事件
在中间件中,需要监听 req 对象的 data 事件,来获取客户端发送到服务器的数据。
如果数据量比较大,无法一次性发送完毕,则客户端会把数据切割后,分批发送到服务器。所以 data 事件可能会触发多次(也就是说每发送过来一次数据,都会触发一次data事件),每一次触发 data 事件时,获取到数据只是完整数据的一部分,需要手动对接收到的数据进行拼接。
如下:
监听 req 的 end 事件
当请求体数据接收完毕之后,会自动触发 req 的 end 事件。
因此,我们可以在 req 的 end 事件中,拿到并处理完整的请求体数据。示例代码如下:
使用 querystring 模块解析请求体数据
Node.js 内置了一个 querystring 模块,专门用来处理查询字符串。通过这个模块提供的 parse() 函数,可以轻松把查询字符串,解析成对象的格式。示例代码如下:
将解析出来的数据对象挂载为 req.body
上游的中间件和下游的中间件及路由之间,共享同一份 req 和 res。因此,我们可以将解析出来的数据,挂载为 req 的自定义属性,命名为 req.body,供下游使用。示例代码如下:
将自定义中间件封装为模块
为了优化代码的结构,我们可以把自定义的中间件函数,封装为独立的模块,示例代码如下:
总结以上几个步骤,代码实现如下:
自定义模块部分:
// 导入 Node.js 内置的 querystring 模块
const qs = require('querystring')
const bodyParser = (req, res, next) => {
// 定义中间件具体的业务逻辑
// 1. 定义一个 str 字符串,专门用来存储客户端发送过来的请求体数据
let str = ''
// 2. 监听 req 的 data 事件
req.on('data', (chunk) => {
str += chunk
})
// 3. 监听 req 的 end 事件
req.on('end', () => {
// 在 str 中存放的是完整的请求体数据
// console.log(str)
// TODO: 把字符串格式的请求体数据,解析成对象格式
const body = qs.parse(str)
req.body = body
next()
})
}
module.exports = bodyParser
主程序部分:
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 1. 导入自己封装的中间件模块
const customBodyParser = require('./14.custom-body-parser')
// 2. 将自定义的中间件函数,注册为全局可用的中间件
app.use(customBodyParser)
app.post('/user', (req, res) => {
res.send(req.body)
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
版权声明
本文为[十八岁讨厌编程]所创,转载请带上原文链接,感谢
https://blog.csdn.net/zyb18507175502/article/details/124354863
边栏推荐
- Leetcode? The first common node of two linked lists
- The difference between is and as in Oracle stored procedure
- TIA博途中基于高速计数器触发中断OB40实现定点加工动作的具体方法示例
- Dolphin scheduler integrates Flink task pit records
- Use of GDB
- Longitude and latitude position of provincial capitals in China
- Basic SQL query and learning
- Oracle lock table query and unlocking method
- 聯想拯救者Y9000X 2020
- 切线空间(tangent space)
猜你喜欢
Apache seatunnel 2.1.0 deployment and stepping on the pit
Common types and basic usage of input plug-in of logstash data processing service
Dolphin scheduler source package Src tar. GZ decompression problem
Logstash数据处理服务的输入插件Input常见类型以及基本使用
Dolphin scheduler integrates Flink task pit records
聯想拯救者Y9000X 2020
Ai21 labs | standing on the shoulders of giant frozen language models
Unified task distribution scheduling execution framework
SSM project deployed in Alibaba cloud
OSS cloud storage management practice (polite experience)
随机推荐
Detailed explanation and usage of with function in SQL
Oracle database recovery data
Detailed explanation of Oracle tablespace table partition and query method of Oracle table partition
JS time to get this Monday and Sunday, judge the time is today, before and after today
Information: 2021 / 9 / 29 10:01 - build completed with 1 error and 0 warnings in 11S 30ms error exception handling
Leetcode | 38 appearance array
Detailed explanation of constraints of Oracle table
零拷貝技術
Lenovo Savior y9000x 2020
ACFs file system creation, expansion, reduction and other configuration steps
Core concepts of microservice architecture
Cross carbon market and Web3 to achieve renewable transformation
[multi screen interaction] realize dual multi screen display II: startactivity mode
面试官给我挖坑:URI中的 “//” 有什么用?
Apache Atlas Compilation and installation records
OSS cloud storage management practice (polite experience)
Get the attribute value difference between two different objects with reflection and annotation
Generate 32-bit UUID in Oracle
顶级元宇宙游戏Plato Farm,近期动作不断利好频频
NPM err code 500 solution