当前位置:网站首页>Express middleware ③ (custom Middleware)

Express middleware ③ (custom Middleware)

2022-04-23 13:47:00 Eighteen hates programming

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 :
 Insert picture description here

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 :
 Insert picture description here

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 :

 Insert picture description here

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 :
 Insert picture description here

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 :
 Insert picture description here

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 :
 Insert picture description here

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