In Nodejs, Express commonly used middleware body-parser for parsing, nodejsbody-parser

Source: Internet
Author: User

In Nodejs, Express commonly used middleware body-parser for parsing, nodejsbody-parser

Preface

body-parserIs a very commonexpressMiddleware is used to parse the request body of the post request. The following two lines of code cover most of the scenarios.

app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));

This article starts from a simple example and exploresbody-parser. Asbody-parserFor more information about how to use it, see the official documentation.

Basics

Before proceeding, let's take a look at the message of a POST request, as shown below.

POST /test HTTP/1.1Host: 127.0.0.1:3000Content-Type: text/plain; charset=utf8Content-Encoding: gzipchyingp

Note the following:Content-Type,Content-EncodingAnd message body:

  1. Content-Type: Type and encoding of the Request Message Body. Common types include text/plain, application/json, and application/x-www-form-urlencoded. Common codes include utf8 and gbk.
  2. Content-Encoding: Declares the compression format of the message body. common values include gzip, deflate, and identity.
  3. Message Body: a common text string chyingp.

What does body-parser mainly do?

body-parserThe main points of implementation are as follows:

1. process different types of request bodies, such as text, json, and urlencoded. The format of the corresponding message body is different.

2. process different codes, such as utf8 and gbk.

3. process different compression types, such as gzip and deflare.

4. Handling of other boundaries and exceptions.

I. process different types of request bodies

To facilitate the reader's test, the following examples contain the server and client code. The complete code can be found on the author's github.

Parse text/plain

The client request code is as follows, which adopts the default encoding and does not compress the Request body. The request body type istext/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/plainThe type processing is simple, that is, the splicing of buffer.

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:Content-TypeChangeapplication/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.text/plain, But there are moreJSON.parse().

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 (); // key code res. end ('your nick is $ {json. nick} ')}); server. listen (0, 3000 );

Parse application/x-www-form-urlencoded

The client code is as follows:querystringFormat the Request body to obtain a format similarnick=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:text/plainThe parsing is almost the same, so there will be morequerystring.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 (); // key code res. end ('your nick is $ {body. nick} ')}); server. listen (0, 3000 );

2. process different codes

In many cases, requests from the client are not necessarily the defaultutf8Encoding. At this time, the request body must be decoded.

The client requests are as follows.

1. Encoding Declaration: Add at the end of Content-Type; charset = gbk

2. Request body encoding: iconv-lite is used here to encode the Request body iconv. encode ('program 小 ', encoding)

Var http = require ('http'); var iconv = require ('iconv-lite '); var encoding = 'gbk'; // Request Code var options = {hostname: '2017. 0.0.1 ', port: '000000', path:'/test', method: 'post', headers: {'content-type': 'text/plain; charset = '+ encoding, 'content-encoding': 'identifi', }}; // Note: nodejs itself does not support gbk Encoding, so before sending a request, encode var buff = iconv. encode ('program 小 ', encoding); var client = http. request (options, (res) => {res. pipe (process. stdout) ;}); client. end (buff, encoding );

The server code is as follows. Here there are two more steps: encoding judgment and decoding. First passContent-TypeGet encoding typegbkAnd theniconv-litePerform reverse decoding.

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; // encoding judgment: The obtained value is '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); // decode the operation done (body) ;}) ;}; var server = http. createServer (function (req, res) {parsePostBody (req, (body) =>{ res. end ('your nick is $ {body} ')}) ;}); server. listen (0, 3000 );

3. processing different compression types

Here is an examplegzipCompression example. The client code is as follows:

1. Compression type declaration: the Content-Encoding value is gzip.

2. Request body compression: gzip compression is performed on the Request body through the zlib module.

Var http = require ('http'); var zlib = require ('zlib '); var options = {hostname: '2017. 0.0.1 ', port: '000000', path:'/test', method: 'post', headers: {'content-type': 'text/plain ', 'content-encoding': 'gzip '}; var client = http. request (options, (res) => {res. pipe (process. stdout) ;}); // Note: When you set Content-Encoding to gzip, the data sent to the server should also be synchronized to gzw.ar buff = zlib.gzip Sync ('chingp '); client. end (buff );

The server code is as follows:zlibModule to understand the compression operation (guzip) of the Request body ).

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; // the key code is 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. end ('your nick is $ {body} ')}) ;}); server. listen (0, 3000 );

Post

body-parserThe core implementation of is not complex. After looking at the source code, you will find that more code is dealing with exceptions and boundaries.

In addition, there is also a very common POST requestContent-TypeYesmultipart/form-dataThe processing is more complex,body-parserIt is not intended to be supported. The length is limited. Continue with the subsequent chapters.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.