Body-parser node. JS (Express) HTTP request Body Parsing middleware
June 08, 2016 781 statement
In an HTTP request, POST
PUT
and PATCH
three request methods containing the request body, node. JS Native HTTP module, the request body to be based on the flow of the way to receive and parse. body-parser
is an HTTP request body parsing middleware, using this module can parse JSON, Raw, text, url-encoded format of the request body, the Express
framework is to use this module as the request body parsing middleware.
- Request Body Parsing
- 1.1 Parsing in native environments
- 1.2 Using the
body-parser
parse request body
- Request Body Parsing
- 2.1
bodyParser.json()
-Parsing JSON format
- 2.2
bodyParser.raw()
-Parsing the binary format
- 2.3
bodyParser.text()
-Parsing text format
- 2.4
bodyParser.urlencoded()
-Parsing text format
1. Request body resolution 1.1 parsing in native environment
The node. JS Native HTTP module, which encapsulates the user request data into a Request object req
, is a single object that is IncomingMessage
also a readable stream object. In a native HTTP server, or without relying on a third-party parsing module, you can receive and parse the request body as follows:
Const HTTP = require (' http ');//Create an HTTP server with 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 resolution //... } else if (req.headers[' Content-type '].indexof (' Text/plain ')!==-1) { // Text text Format request body resolution //... } else if (req.headers[' Content-type '].indexof (' application/x-www-form-urlencoded ')! ==-1) { //url-encoded format Request body resolution //... } else {/ other format parsing }} ) } else { res.end (' Other submission methods '); }). Listen (3000);
1.2 Use
body-parser
Parsing the request body
body-parser
Module is a Express/Connect
middleware, it is very simple and powerful, you can use this module as follows to parse the request body:
Express/connect Item Layer Processing
Express
The framework defaults body-parser
to use as the request body parsing middleware, after creating the Express project, you can app.js
see the following code in the file:
/* Introduce dependencies */var Express = require (' Express ');//... var bodyparser = require (' Body-parser '); var routes = require ('./routes/in Dex '); var users = require ('./routes/users '); var app = Express ();//...//parsing application/jsonapp.use (Bodyparser.json ()); /Parse Application/x-www-form-urlencodedapp.use (bodyparser.urlencoded ());
This introduces the body-parser
module processing request body at the application level of the project. In the code above, the module handles application/x-www-form-urlencoded
application/json
the request body in two different content formats. After this middleware has been processed, the request parameters can be accessed in all routing processors req.body
.
Parsing Express specific routes
In real-world applications, different paths (routes) may require users to use different content types and body-parser
also support the addition of a request body resolution for a single express route:
var express = require (' Express ') var Bodyparser = require (' Body-parser ') var app = Express ()//Create Application/json parse var jso Nparser = Bodyparser.json ()//Create application/x-www-form-urlencoded parse var urlencodedparser = bodyparser.urlencoded ({ Extended:false})//Post/login get URL-encoded request body app.post ('/login ', Urlencodedparser, function (req, res) { if (!req.body) Return Res.sendstatus ( res.send (' Welcome, ' + req.body.username)})//Post/api/users get JSON-encoded request body app.post ('/ Api/users ', Jsonparser, function (req, res) { if (!req.body) return Res.sendstatus (+) //create user in Req.body })
Specify request type
body-parser
It also supports specifying the resolution for the request body of one or a class of content types, specifying the parsing method that can be modified by adding parameters in the parsing methods type
Content-Type
.
For example, you can text/plain
use parsing for content types JSON
:
App.use (Bodyparser.json ({type: ' Text/plain '})
This option is more used in the parsing of non-standard request headers, as follows:
Resolves custom jsonapp.use (Bodyparser.json ({type: ' Application/*+json '})//resolves custom bufferapp.use (Bodyparser.raw ({type: ') Application/vnd.custom-type '})//HTML request body As String processing App.use (Bodyparser.text ({type: ' text/html '})
2.
body-parser
API for Modules
npm install body-parser
After you install the module by command, you can obtain the module reference in the following ways:
var bodyparser = require (' Body-parser ')
bodyParser
A variable is a reference to a middleware. After the request body is parsed, the parsed value is placed into the req.body
property, and the content is empty when it is an {}
empty object.
2.1
bodyParser.json()
-Parse JSON format
Bodyparser.json (Options)
Returns a json
middleware that parses only formatted data. This method supports arbitrary Unicode-encoded request bodies, and supports gzip
and deflate
encodes data compression.
option is an object that contains the following optional values
inflate
-When set to, compressed data is decompressed, true
deflate
and when set to true
, deflate
compressed data is rejected. The default is true
.
limit
-Set the maximum amount of data requested. Default is‘100kb‘
reviver
- JSON.parse()
The second parameter passed to the method, see Json.parse ()
strict
-When set to true
, only resolves Array
and Object
two formats, set to false
resolve all JSON.parse
supported formats. Default istrue
type
-This option is used to set the current parsing middleware for data of the specified MIME type. This option can be a function or a string, when the string is used Type-is to find the Mimi type, and when the function is, the middleware passes fn(req)
to get the actual value. The default is application/json
.
verify
-This option is only verify(req, res, buf, encoding)
supported at the time
2.2
bodyParser.raw()
-Parse binary format
Bodyparser.raw (Options)
Returns a middleware that handles all data as a Buffer
format. This method supports gzip
and deflate
encodes the data compression. After parsing, all subsequent will be req.body
a Buffer
data.
option is an object that contains the following optional values
inflate
-When set to, compressed data is decompressed, true
deflate
and when set to true
, deflate
compressed data is rejected. The default is true
.
limit
-Set the maximum amount of data requested. Default is‘100kb‘
type
-This option is used to set the current parsing middleware for data of the specified MIME type. This option can be a function or a string, when the string is used Type-is to find the Mimi type, and when the function is, the middleware passes fn(req)
to get the actual value. The default is application/octet-stream
.
verify
-This option is only verify(req, res, buf, encoding)
supported at the time
2.3
bodyParser.text()
-Parse Text Format
Bodyparser.text (Options)
Returns a middleware that handles string format processing only. This method supports gzip
and deflate
encodes the data compression. After parsing, all subsequent will be req.body
a string value.
option is an object that contains the following optional values
defaultCharset
- Content-Type
Use this encoding if the encoding is not specified later. Default is‘utf-8‘
inflate
-When set to, compressed data is decompressed, true
deflate
and when set to true
, deflate
compressed data is rejected. The default is true
.
limit
-Set the maximum amount of data requested. Default is‘100kb‘
type
-This option is used to set the current parsing middleware for data of the specified MIME type. This option can be a function or a string, when the string is used Type-is to find the Mimi type, and when the function is, the middleware passes fn(req)
to get the actual value. The default is application/octet-stream
.
verify
-This option is only verify(req, res, buf, encoding)
supported at the time
2.4
bodyParser.urlencoded()
-Parse Text Format
bodyparser.urlencoded (Options)
Returns a urlencoded
middleware that processes data. This method uses UTF-8 encoding by default, and supports gzip
and deflate
encodes data compression. After parsing, all subsequent will be req.body
a key-value pair object.
option is an object that contains the following optional values
extended
-When set to false
, the URL-encoded data is parsed using the QueryString Library, and the true
URL-encoded data is parsed using the library when set to qs
. This encoding is used when no encoding is specified. Default istrue
inflate
-When set to, compressed data is decompressed, true
deflate
and when set to true
, deflate
compressed data is rejected. The default is true
.
limit
-Set the maximum amount of data requested. Default is‘100kb‘
parameterLimit
-The maximum data used to set the URL encoding value. Default is1000
type
-This option is used to set the current parsing middleware for data of the specified MIME type. This option can be a function or a string, when the string is used Type-is to find the Mimi type, and when the function is, the middleware passes fn(req)
to get the actual value. The default is application/octet-stream
.
verify
-This option is only verify(req, res, buf, encoding)
supported at the time
Body-parser node. JS (Express) HTTP request Body parsing middleware