Nodejs makes custom middleware

I think you all know about Nodejs middleware. Next, I will take making a custom middleware for processing form data as an example to tell you how to make your own custom middleware.

1. Create a util.js file to encapsulate and write custom form data processing middleware

// 导入querystring模块(目的是用于将下方拼接好的查询字符串转换成对象)
const qs = require('querystring')

//创建中间件处理函数
function bodyParser(req, res, next) {
  let str = ''
  // 这个chunk就是每次获取到的请求体的部分数据
  req.on('data', (chunk) => {
    str += chunk
  })

  req.on('end', () => {
    const body = qs.parse(str)
    //这里将处理好的请求体数据挂载到req上
    // 就是为了让后边的路由可以通过req.body获取到
    req.body = body
    next() //将流转关系传递给后边的中间件或路由
  })
}

//导出中间件函数
module.exports = bodyParser

2. Create an app.js file for creating services and registering middleware

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

// 创建服务器对象
const app = express()

// 1.导入自定义的中间件模块
const bodyparser = require('./util.js')

// 2.注册自定义的中间件  将其注册为全局可用的中间件

app.use(bodyparser)

app.post('/test', (req, res) => {
  //由于全局注册过自定义的处理请求体表单数据的中间件,所以这里可以直接获取到请求体数据
  // 如果过没有注册过处理表单数据的中间件,这里req.body的返回值将会是undefined
  res.send(req.body)
})

//启动服务器
app.listen(80, () => {
  console.log('express server running at http://127.0.0.1');
})

3. Effect test

Run the app.js file in the integrated terminal to start the service

Open postman, 1. Select the post request method, and enter http://127.0.0.1/test in the address bar. 2. Select the Body option.

3. Select x-www-form-urlendcoded 4. Fill in the request body form data 5. Send the request

As can be seen from the figure below, after the request is sent, the server returns the request body object, indicating that the custom middleware takes effect

 

 

Guess you like

Origin blog.csdn.net/LLL3189860667/article/details/126945471
Recommended