body-parser Node.js(Express) HTTP request body parsing middleware
Statement 781 on June 8, 2016
In the HTTP request, the request body is included in the three request methods POST
, PUT
and PATCH
in the Node.js native HTTP module, the request body must be received and parsed based on the flow. body-parser
It is an HTTP request body parsing middleware. Using this module, you can parse the request body in JSON, Raw, text, and URL-encoded formats. The Express
framework uses this module as the request body parsing middleware.
1. Request body parsing
1.1 Analysis in the native environment
In the Node.js native HTTP module, the user request data is encapsulated into the request object req
, which IncomingMessage
is a readable stream object. On a native HTTP server, or without relying on a third-party parsing module, the request body can be received and parsed as follows:
const http = require('http'); //Create an http server with the http module http.createServer(function(req, res) { if (req.method.toLowerCase() === 'post') { var body = ''; req.on('data', function(chunk){ body += chunk; }); req.on('end', function(){ if(req.headers['content-type'].indexOf('application/json')!==-1){ // JSON format request body parsing JSON.parse(body); } else if(req.headers['content-type'].indexOf('application/octet-stream')!==-1){ // Raw format request body parsing // …… } else if(req.headers['content-type'].indexOf('text/plain')!==-1){ // text text format request body parsing // …… } else if(req.headers['content-type'].indexOf('application/x-www-form-urlencoded')!==-1){ // URL-encoded format request body parsing // …… } else { // Other format parsing } }) } else { res.end('Other submission methods'); } }).listen(3000);
1.2 Use body-parser
parsing request body
body-parser
A module is a Express/Connect
middleware that is very simple and powerful to use. You can use this module to parse the request body like this:
Express/Connect item level processing
Express
body-parser
The framework uses the request body parsing middleware by default . After creating the Express project , you can app.js
see the following code in the file:
/* import dependencies */ var express = require('express'); // …… var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express (); // …… // Parse application/json app.use(bodyParser.json()); // 解析 application/x-www-form-urlencoded app.use(bodyParser.urlencoded());
In this way, at the Application level of the project , a body-parser
module is introduced to process the request body. In the above code, the module will process the request body application/x-www-form-urlencoded
in application/json
two content formats. After processing by this middleware, req.body
request parameters can be accessed in all route handlers.
Parse Express specific routes
In practical applications, different paths (routes) may require users to use different content types. body-parser
It also supports adding request body parsing for a single Express route :
var express = require('express') var bodyParser = require('body-parser') var app = express () // Create application/json parsing var jsonParser = bodyParser.json () // Create application/x-www-form-urlencoded parsing var urlencodedParser = bodyParser.urlencoded({ extended: false }) // POST /login to get the URL-encoded request body app.post('/login', urlencodedParser, function (req, res) { if (!req.body) return res.sendStatus(400) res.send('welcome, ' + req.body.username) }) // POST /api/users to get JSON-encoded request body app.post('/api/users', jsonParser, function (req, res) { if (!req.body) return res.sendStatus(400) // create user in req.body })
Specify the request type
body-parser
It also supports specifying the parsing method for the request body of a certain or a class of content types. When specifying, you can modify the specified parsing method by adding type
parameters to Content-Type
the parsing method.
For example, you can use parsing on the text/plain
content type :JSON
app.use(bodyParser.json({ type: 'text/plain' }))
This option is more used in the parsing of non-standard request headers, as follows:
// Parse custom JSON app.use(bodyParser.json({ type: 'application/*+json' })) // Parse custom Buffer app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) // Process the HTML request body as a string app.use(bodyParser.text({ type: 'text/html' }))
2. body-parser
Module API
After installing the module via npm install body-parser
command, the module reference can be obtained by:
var bodyParser = require('body-parser')
bodyParser
Variables are references to middleware. After the request body is parsed, the parsed value will be put into req.body
the attribute, and if the content is empty, it will be an {}
empty object.
2.1 bodyParser.json()
- Parsing JSON format
bodyParser.json(options)
Returns a middleware that only parses json
formatted data. This method supports arbitrary Unicode-encoded request bodies, and supports gzip
and deflate
encoded data compression.
Option is an object containing the following optional values
inflate
-true
When set to ,deflate
compressed data will betrue
decompressed to ,deflate
compressed data will be rejected. Default istrue
.limit
- Set the maximum amount of data requested. The default is'100kb'
reviver
JSON.parse()
- The second parameter passed to the method, see JSON.parse() for detailsstrict
-true
When set to, only two formats will be parsedArray
;Object
set tofalse
will parse allJSON.parse
supported formats. The default istrue
type
- This option is used to set the current parsing middleware to be used for data of the specified MIME type. This option can be a function or a string. When it is a string, it will use type-is to find the MIMI type; when it is a function, the middleware willfn(req)
get the actual value through it. Default isapplication/json
.verify
- This option is onlyverify(req, res, buf, encoding)
supported when
2.2 bodyParser.raw()
- Parsing binary format
bodyParser.raw(options)
Buffer
Returns a middleware that handles all data as a format. This method supports gzip
and deflate
encodes data compression. After parsing, all the req.body
following will be a Buffer
data.
Option is an object containing the following optional values
inflate
-true
When set to ,deflate
compressed data will betrue
decompressed to ,deflate
compressed data will be rejected. Default istrue
.limit
- Set the maximum amount of data requested. The default is'100kb'
type
- This option is used to set the current parsing middleware to be used for data of the specified MIME type. This option can be a function or a string. When it is a string, it will use type-is to find the MIMI type; when it is a function, the middleware willfn(req)
get the actual value through it. Default isapplication/octet-stream
.verify
- This option is onlyverify(req, res, buf, encoding)
supported when
2.3 bodyParser.text()
- Parsing text format
bodyParser.text(options)
Returns a middleware that only handles string formatting. This method supports gzip
and deflate
encodes data compression. After parsing, all following req.body
will be a string value.
Option is an object containing the following optional values
defaultCharset
- IfContent-Type
no encoding is specified after, this encoding is used. The default is'utf-8'
inflate
-true
When set to ,deflate
compressed data will betrue
decompressed to ,deflate
compressed data will be rejected. Default istrue
.limit
- Set the maximum amount of data requested. The default is'100kb'
type
- This option is used to set the current parsing middleware to be used for data of the specified MIME type. This option can be a function or a string. When it is a string, it will use type-is to find the MIMI type; when it is a function, the middleware willfn(req)
get the actual value through it. Default isapplication/octet-stream
.verify
- This option is onlyverify(req, res, buf, encoding)
supported when
2.4 bodyParser.urlencoded()
- Parsing text format
bodyParser.urlencoded(options)
Returns a urlencoded
middleware that handles data. This method uses UTF-8 encoding by default, and supports gzip
and deflate
encoded data compression. After parsing, all subsequent req.body
entries will be a key-value object.
Option is an object containing the following optional values
extended
- Whenfalse
set to , use the querystringtrue
library to parse URL-encoded data; when set to , useqs
the library to parse URL-encoded data. When no encoding is specified after, this encoding is used. The default istrue
inflate
-true
When set to ,deflate
compressed data will betrue
decompressed to ,deflate
compressed data will be rejected. Default istrue
.limit
- Set the maximum amount of data requested. The default is'100kb'
parameterLimit
- Maximum data for setting URL encoded values. The default is1000
type
- This option is used to set the current parsing middleware to be used for data of the specified MIME type. This option can be a function or a string. When it is a string, it will use type-is to find the MIMI type; when it is a function, the middleware willfn(req)
get the actual value through it. Default isapplication/octet-stream
.verify
- This option is onlyverify(req, res, buf, encoding)
supported when