Implementation method of Express middleware body-parser

不言
Release: 2019-04-11 10:26:41
forward
2373 people have browsed it

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(); }); }
Copy after login

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);
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!