EXPRESS Common Middleware Body-Parser Implementation Analysis in NodeJs

Write in front

Body-Parser is a very commonly used Express middleware, and the action is a request for POST request Elignment. It is very simple to use. The following two lines of code have covered most of the use scenarios.

app.use (bodyparser.json ()); app.use (bodyparser.urlencoded ({extended: false});
   
From a simple example, inquiry Body-Parser
. As for

Body-Parser How to use, students can refer to the official documentation. Getting Started Basis

Before the official explanation, let’s first look at the packets requested by the POST, as shown below.

POST / TEST HTTP / 1.1HOST: 127.0.0.1:3000Content-Type: Text / Plain; Charset = UTF8Content-Encoding: Gzipchyingp


There is a need for us to pay attention to
 Content-Type ,  Content-Encoding 
and the main body of the message:

Content -Type: Request the type of message entity, encoding. Common types include Text / Plain, Application / JSON, Application / X-WWW-FORM-URLENCODED. Common codes are UTF8, GBK, etc. ContenT-Encoding: Declaration of the compressed format of the main body of the message, the common value is Gzip, deflate, Identity. News main body: Here is a normal text string chyingp.

What is mainly made
  1. The points achieved by Body-Parser
  2. are as follows:
1. Handling different types of requests: such as Text, JSON, URLENCoded, etc., the corresponding packet main body is different.

2. Handling different coding: such as UTF8, GBK, etc.

3. Handling different compression types: such as Gzip, Deflare, etc.

4. Other boundaries, abnormalities.

For different types of requests


In order to facilitate the reader test, the following example includes the server, client code, and complete code can be found on the author Github.


Analysis of Text / Plain

The code of the client request is as follows, using default encoding, and does not compress the request body. The requested body 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’}}; varclient = HTTP.Request (options, (res) => {res., “; client.end (‘chyingp’);

The server code is as follows .

Text / Plain Type processing is relatively simple, it is buffer splicing.

VAR http = request (‘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. is $ {body} `)}) Server.Listen (3000);

Analysis Application / JSON
 The client code is as follows,  content- TYPE  is replaced with 
Application / JSON .

Var http = request ('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 to
Text / Plain. , only the process of
 json.parse () .  
VAR http = request (‘http’); var parsepostbody = function (req, done) {var longth = Req.Headers [‘content-length’] – 0 VAR Arr = []; var chunks; Req.on (‘data’, 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 ()); // Key code RES.END (`Your Nick IS $ {JSON.NICK}`)};}); Server.Listen (3000);

Analysis Application / X-WWW -form-urlencoded

The client code is as follows, and the request body is formatted by queryString to obtain 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);
  The server code is as follows, and the analysis of  text / plain 
is similar, more The 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 (ref, res) {ParsepostBody (Req, (chunks) => {var Body = queryString.Parse (chunks.tostring ()); // Key code res., (`Your Nick IS $ {body.nick})});}; server.listen (3000);

Second, processing different coding
  Waiting, from the client's request, it is not necessarily the default 
UTF8 encoding. At this time, the request body needs to decode processing.

The client request is as follows, there are two main points.

1. Coding declaration: Last plus in Content-Type; Charset = GBK

2. Request Body Code: Here, ICONV-LITE, the request body Code Iconv.Encode (‘Program Card’, Encoding)

VAR http = required (‘http’); var iConv = Require (‘iconv-limited ” ); var encoding = ‘gbk’; // Request Code VAR Options = {Hostname: ‘127.0.0.1’, Port: ‘3000’, Path: ‘/ Test’, Method: ‘POST’, Headers: {‘Content- TYPE ‘:’ text / place; charset = ‘+ encoding,’ content-encoding ‘:’ Identity ‘,}}; // Note: Nodejs itself does not support GBK encoding, so before the request is sent, you need to code VAR BUFF = Iconv.Encode (‘Program Card’, Encoding); Var Client = Http.Request (options, (res) => {res.pipe (process.stdout);}; client.end (buff, eNCoding);
   The server code is as follows, here more than two steps: encoding judgment, decoding operation. First pass 
Content-Type Get encoding type
GBK

, and then reverse decoding operation by ICONV-LITE .

VAR http = require (‘http’); var contentType = Require (‘content-type’); var iconv = required (‘iconv-lite’); var PARSEPOSTBODY = Function (REQ, DONE) {var obj = contenttype.parse (Req.Headers [‘content-type’]); var charset = obj.parameters.charset; // Code judgment: The value obtained here is’ GBK ‘var arr = []; var chunks; req.on (‘ data ‘, buff);}; req.on (‘ end “, () => {chunks = buffer.concat (arr); var body = iconv.decode (chunks, charset); // Decoding operation done (body);}; var server = http.createserver (req, res) {ParsepostBody (Req, (Body) ) => {RES $ {body}})});}); Server.Listen (3000);
   
three Handling different compression types
An example of the compression of

Gzip here. The client code is as follows:

1. Compression type declaration: content-encoding assigns Gzip. 2. Request body compression: Gzip compression of the request body via the ZLIB module.


VAR http = request (‘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 ‘}}; varclient = http.request Options, (res) => {res. // Note: While setting the content-encoding to Gzip, the data sent to the server should also perform GzipVar buff = Zlib.gzipsync. ‘chyingp’); Client.End (BUFF);

The server code is as follows, here is used to understand the compression operation by
ZLIB

module. (Guzip).

VAR http = request (‘http’); var zlib = request (‘zlib’); var parsepostbody = function (Req,DONE) {var longth = Req.Headers [‘content-length’] – 0; var contentEncoding = Req.Headers [‘content-encoding’]; var stream = req; // Key code as follows 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. is $ {body} ` )});}); Server.Listen (3000);
  Written in the back  
body-parse

The core implementation is not complicated. After the source code you will find, more code is dealing with an exception and boundary. In addition,For Post request, there is also a very common Content-Type is Multipart / Form-Data , this processing is relatively complex,

body-paser
is not intended Support it. The space is limited, and the subsequent chapter will continue to start.
  The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Clouds.  
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment