Home Web Front-end JS Tutorial Detailed explanation of examples of commonly used middleware body-parser in Nodejs

Detailed explanation of examples of commonly used middleware body-parser in Nodejs

May 23, 2017 pm 01:25 PM
body express nodejs parser

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

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

Among them, we need to pay attention to Content-Type, Content-Encoding and the message body:

  1. 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.

  2. Content-Encoding: Declares the compression format of the message body. Common values ​​include gzip, deflate, and identity.

  3. Message body: This is an ordinary text Stringchyingp.

What body-parser mainly does

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

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

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

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

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

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

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

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

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

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

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

Can nodejs write front-end? Can nodejs write front-end? Apr 21, 2024 am 05:00 AM

Yes, Node.js can be used for front-end development, and key advantages include high performance, rich ecosystem, and cross-platform compatibility. Considerations to consider are learning curve, tool support, and small community size.

See all articles