Home > Article > Web Front-end > Implementation method of Express middleware body-parser
The content of this article is about the implementation method of Express middleware body-parser. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The previous article wrote about how to use body-parser middleware to process post requests. Today I will roughly implement the urlencoded method in body-parser.
First enter mkdir lib && cd lib through the command prompt.
Enter touch body-parser.js.
Type the following code in body-parser.js.
// lib/body-parser.js const querystring = require('querystring'); module.exports.urlencoded = function (req, res, next) { let chunks = []; req.on('data', data => { chunks.push(data); }); req.on('end', () => { // 合并Buffer。 let buf = Buffer.concat(chunks).toString(); // 把querystring解析过的json 放到 req.body上。 req.body = querystring.parse(buf); next(); }); }
The following is the main program code.
// app.js const express = require('express'); const bodyParser = require('./lib/body-parser'); let app = express(); app.use(bodyParser.urlencoded); app.post('/', (req, res) => { res.send(req.body); }); app.listen(8000);
Now we have completed the function similar to the body-parser middleware. Req.body has the requested post data.
【Related recommendations: JavaScript video tutorial】
The above is the detailed content of Implementation method of Express middleware body-parser. For more information, please follow other related articles on the PHP Chinese website!