express custom middleware handles post requests

preface

express's built-in urlencoded () has compatibility problems. We use node's querystring to encapsulate a middleware for processing post requests for ease of use.

1, Built in middleware (common)

Implementation code and notes

const express = require('express');
const app = express();

// Built in middleware common
// express.static() sets the static directory
// express.json() accepts data in json format 
    // [data format: {id:1,name:"222"}, request header: application/json]
// express.urlencoded() handles post form data
    // [data format: id = 1 & name = 222, request header: application/x-www-form-urlencoded]

// The middleware should pay attention to the use position before the request and after the response
// After receiving the data, the object form of the data will be attached to the body attribute of the req request object
// Both middleware have compatibility problems, and there are few subsequent uses
app.use(express.urlencoded({extended:false})) // The function of extended is to obtain whether the passed object has a far prototype
app.use(express.json())
app.post('/',(req, res)=>{
    console.log(req.body);
})
app.listen(3000,()=>{
    console.log("server is running at http://localhost:3000");
})
  • Now let's send the request
  • Check in the background. The post request data has been parsed

2, Encapsulating middleware to handle post requests

1. How to package

  • Most of the form data is submitted to the server by post. You need to listen to the data event of the req object (receiving the data submitted by the request) to obtain the data sent by the client to the server. If the amount of data is large and cannot be sent at one time, the client will cut the data and send it to the server in batches. Therefore, the data event may be triggered many times. Each time the data event is triggered, the received data is only a part of all the data. Therefore, it is necessary to splice the data to obtain the complete data:
const querystring = require('querystring');
function postparse (req,res, next){
    let arr = [];  // Data may be sent in batches. A container is defined here
    // Listen for data events 
    req.on('data',buffer=>{
        arr.push(buffer);   // buffer means that the data transmitted each time is put into the arr in batches; 
        console.log(buffer); // buffer is hexadecimal data and is not readable
    }) 
    // The end event will be triggered after transmission. Listen for the end event
    req.on("end",()=>{
		// Buffer.concat(arr) is used to splice buffer data in arr and then tostring into characters
		// Then querystring Parse() to object
        let post = querystring.parse(Buffer.concat(arr).toString())
        // Mount to req On the body
        req.body = post
         // Continue the subsequent request processing (the end event processing is asynchronous, so the next must be written in the function)
        next();
    }); 
}
module.exports = postparse;
  • Use middleware
// Custom middleware is essentially a function
// In the whole request link, all middleware and the final route share a req, res
const express = require('express');
const postparse = require('./middleware/postparse');
const app = express();
app.use(postparse)
app.post('/',(req,res)=>{
    console.log(req.body);
    res.send('Sent successfully ')
})
app.listen(3000,()=>{
    console.log("server is running at  http://localhost:3000" );
})
  • Output the buffer as hexadecimal data. First convert it into character and then object, which is convenient for calling

3, Third party Middleware

  • Third party middleware can be installed and used, which is more convenient

  • Taking the use of body parser middleware to receive post data as an example, the steps are as follows:

  • Install the third-party middleware body parser

  • npm i -S body-parser

  • Import body parser from application file

  • Call app through middleware use(body.urlencoded({extended: false}))

  • Pass req. In the matching route Body gets data in post

    • Express built-in express Urlencoded middleware is further encapsulated based on the third-party middleware body parser. However, the built-in version is incompatible, so the general project chooses to install and use the third-party middleware

When using, the syntax of the body parser library is the same as the built-in express The syntax of urlencoded middleware is very similar because the built-in middleware is implemented based on body parser.

  • Using body parse
const express = require('express')
const app = express()

// Introducing body parser
const bodyParser = require('body-parser')
// Using body parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));

app.post('/',(req,res) => {
    console.log(req.body);
    res.send("send out ok")
})

app.listen(3000,() => {
    console.log("Server is running at http://127.0.0.1:3000")
})

summary

  • A post request middleware is roughly encapsulated. Although the third-party middleware is convenient, understanding its general principle is helpful for memory and learning

Keywords: node.js Middleware post express

Added by accident on Sat, 15 Jan 2022 20:54:46 +0200