Home > Article > Web Front-end > Detailed explanation of examples of commonly used middleware body-parser in Nodejs
This article mainly introduces the common Express middleware body-parser in Nodejs to implement parsing, which has certain reference value. Interested friends can refer to it
Written in front
body-parser
is a very commonly used express
middleware, which is used to parse the request body of post request. It is very simple to use. The following two lines of code have covered most of the usage scenarios.
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
This article starts from a simple example and explores the internal implementation of body-parser
. As for how to use body-parser
, interested students can refer to the official documentation.
Getting Started Basics
Before the formal explanation, let’s first look at a POST request message, as shown below.
POST /test HTTP/1.1 Host: 127.0.0.1:3000 Content-Type: text/plain; charset=utf8 Content-Encoding: gzip chyingp
Among them, we need to pay attention to Content-Type
, Content-Encoding
and the message body:
Content -Type: The type and encoding of the request message body. Common types include text/plain, application/json, application/x-www-form-urlencoded. Common encodings include utf8, gbk, etc.
Content-Encoding: Declares the compression format of the message body. Common values include gzip, deflate, and identity.
Message body: This is an ordinary text Stringchyingp.
What body-parser mainly does
body-parser
The key points of implementation are as follows:
1. Process different types of request bodies: such as text, json, urlencoded, etc. The corresponding message body formats are different.
2. Handle different encodings: such as utf8, gbk, etc.
3. Handle different compression types: such as gzip, deflare, etc.
4. Handling of other boundaries and exceptions.
1. Processing different types of request bodies
In order to facilitate readers' testing, the following examples include server and client code. The complete code can be found on the author's github.
Parse text/plain
The code requested by the client is as follows, using the default encoding and not compressing the request body. The request body type is text/plain
.
var http = require('http'); var options = { hostname: '127.0.0.1', port: '3000', path: '/test', method: 'POST', headers: { 'Content-Type': 'text/plain', 'Content-Encoding': 'identity' } }; var client = http.request(options, (res) => { res.pipe(process.stdout); }); client.end('chyingp');
The server code is as follows. text/plain
Type processing is relatively simple, it is the splicing of buffers.
var http = require('http'); var parsePostBody = function (req, done) { var arr = []; var chunks; req.on('data', buff => { arr.push(buff); }); req.on('end', () => { chunks = Buffer.concat(arr); done(chunks); }); }; var server = http.createServer(function (req, res) { parsePostBody(req, (chunks) => { var body = chunks.toString(); res.end(`Your nick is ${body}`) }); }); server.listen(3000);
Parse application/json
The client code is as follows, replace Content-Type
with application/json
.
var http = require('http'); var querystring = require('querystring'); var options = { hostname: '127.0.0.1', port: '3000', path: '/test', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Encoding': 'identity' } }; var jsonBody = { nick: 'chyingp' }; var client = http.request(options, (res) => { res.pipe(process.stdout); }); client.end( JSON.stringify(jsonBody) );
The server code is as follows. Compared with text/plain
, it just has an additional JSON.parse()
process.
var http = require('http'); var parsePostBody = function (req, done) { var length = req.headers['content-length'] - 0; var arr = []; var chunks; req.on('data', buff => { arr.push(buff); }); req.on('end', () => { chunks = Buffer.concat(arr); done(chunks); }); }; var server = http.createServer(function (req, res) { parsePostBody(req, (chunks) => { var json = JSON.parse( chunks.toString() ); // 关键代码 res.end(`Your nick is ${json.nick}`) }); }); server.listen(3000);
Parse application/x-www-form-urlencoded
The client code is as follows, where the request body is formatted through querystring
, Get a string similar to nick=chyingp
.
var http = require('http'); var querystring = require('querystring'); var options = { hostname: '127.0.0.1', port: '3000', path: '/test', method: 'POST', headers: { 'Content-Type': 'form/x-www-form-urlencoded', 'Content-Encoding': 'identity' } }; var postBody = { nick: 'chyingp' }; var client = http.request(options, (res) => { res.pipe(process.stdout); }); client.end( querystring.stringify(postBody) );
The server code is as follows, which is similar to the parsing of text/plain
, with the addition of a call to querystring.parse()
.
var http = require('http'); var querystring = require('querystring'); var parsePostBody = function (req, done) { var length = req.headers['content-length'] - 0; var arr = []; var chunks; req.on('data', buff => { arr.push(buff); }); req.on('end', () => { chunks = Buffer.concat(arr); done(chunks); }); }; var server = http.createServer(function (req, res) { parsePostBody(req, (chunks) => { var body = querystring.parse( chunks.toString() ); // 关键代码 res.end(`Your nick is ${body.nick}`) }); }); server.listen(3000);
2. Handling different encodings
Many times, the request from the client does not necessarily use the default utf8
encoding. At this time , you need to decode the request body.
The client request is as follows, there are two main points.
1. Encoding statement: Add;charset=gbk at the end of Content-Type
2. Request body encoding: iconv-lite is used here to encode the request body Encode iconv.encode('Programmer Xiaoka', encoding)
var http = require('http'); var iconv = require('iconv-lite'); var encoding = 'gbk'; // 请求编码 var options = { hostname: '127.0.0.1', port: '3000', path: '/test', method: 'POST', headers: { 'Content-Type': 'text/plain; charset=' + encoding, 'Content-Encoding': 'identity', } }; // 备注:nodejs本身不支持gbk编码,所以请求发送前,需要先进行编码 var buff = iconv.encode('程序猿小卡', encoding); var client = http.request(options, (res) => { res.pipe(process.stdout); }); client.end(buff, encoding);
The server code is as follows. There are two more steps here: encoding judgment and decoding operation. First obtain the encoding type gbk
through Content-Type
, and then perform the reverse decoding operation through iconv-lite
.
var http = require('http'); var contentType = require('content-type'); var iconv = require('iconv-lite'); var parsePostBody = function (req, done) { var obj = contentType.parse(req.headers['content-type']); var charset = obj.parameters.charset; // 编码判断:这里获取到的值是 'gbk' var arr = []; var chunks; req.on('data', buff => { arr.push(buff); }); req.on('end', () => { chunks = Buffer.concat(arr); var body = iconv.decode(chunks, charset); // 解码操作 done(body); }); }; var server = http.createServer(function (req, res) { parsePostBody(req, (body) => { res.end(`Your nick is ${body}`) }); }); server.listen(3000);
3. Handling different compression types
Here is an example of gzip
compression. The client code is as follows, and the key points are as follows:
1. Compression type declaration: Content-Encoding is assigned gzip.
2. Request body compression: gzip compress the request body through the zlib module.
var http = require('http'); var zlib = require('zlib'); var options = { hostname: '127.0.0.1', port: '3000', path: '/test', method: 'POST', headers: { 'Content-Type': 'text/plain', 'Content-Encoding': 'gzip' } }; var client = http.request(options, (res) => { res.pipe(process.stdout); }); // 注意:将 Content-Encoding 设置为 gzip 的同时,发送给服务端的数据也应该先进行gzip var buff = zlib.gzipSync('chyingp'); client.end(buff);
The server code is as follows. Here, the request body is decompressed (guzip) through the zlib
module.
var http = require('http'); var zlib = require('zlib'); var parsePostBody = function (req, done) { var length = req.headers['content-length'] - 0; var contentEncoding = req.headers['content-encoding']; var stream = req; // 关键代码如下 if(contentEncoding === 'gzip') { stream = zlib.createGunzip(); req.pipe(stream); } var arr = []; var chunks; stream.on('data', buff => { arr.push(buff); }); stream.on('end', () => { chunks = Buffer.concat(arr); done(chunks); }); stream.on('error', error => console.error(error.message)); }; var server = http.createServer(function (req, res) { parsePostBody(req, (chunks) => { var body = chunks.toString(); res.end(`Your nick is ${body}`) }); }); server.listen(3000);
Written at the back
The core implementation of body-parser
is not complicated. After looking at the source code, you will find that there are more codes It's handling exceptions and boundaries.
In addition, for POST requests, there is a very common Content-Type
which is multipart/form-data
. The processing of this is relatively complicated, body-parser
is not intended to support it. The space is limited, so we will continue to expand in subsequent chapters.
【Related Recommendations】
1. Javascript free video tutorial
2. Detailed examples of JS implementation of marquee scrolling effect
3. JS code example for making QQ chat message display and comment submission function
4. Single line of JS to implement mobile money format verification
5. JavaScript form verification implementation code_javascript skills
The above is the detailed content of Detailed explanation of examples of commonly used middleware body-parser in Nodejs. For more information, please follow other related articles on the PHP Chinese website!