


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!

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
