自定义中间件

自定义中间件:

// 导入express模块
const express = require('express')

// 创建express的服务器实例
const app = express()

// 1. 导入自己封装的中间件模块
const customBodyParser = require('./017-custom-body-parser')
// 2. 将自定义的中间件函数,注册为全局可用的中间件
app.use(customBodyParser)

app.post('/user', (req, res) => {
  res.send(req.body)
})


// 导入Node.js内置的querystring模块
const qs = require('querystring')

// 解析表单数据的中间件
app.use((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)
        // 调用qs.parse() 方法  把查询字符串解析为对象格式
        const body = qs.parse(str)
        req.body = body
        next()
    })
})

app.post('/user', (req, res) => {
    res.send(req.body)
})
// 调用app.listen方法,指定端口号并启动web服务器
app.listen(80, () => {
    console.log("running http://127.2.1.1")
})
原文地址:https://www.cnblogs.com/lblblibin/p/13556442.html