body-parser Node.js(Express) HTTP request body parsing middleware

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, PUTand PATCHin the Node.js native HTTP module, the request body must be received and parsed based on the flow. body-parserIt 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 Expressframework uses this module as the request body parsing middleware.

  1. Request body parsing
  2. Request body parsing

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 IncomingMessageis 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-parserparsing request body

body-parserA module is a Express/Connectmiddleware 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

Expressbody-parserThe framework uses the request body parsing middleware by default . After creating the Express project , you can app.jssee 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-parsermodule is introduced to process the request body. In the above code, the module will process the request body application/x-www-form-urlencodedin application/jsontwo content formats. After processing by this middleware, req.bodyrequest 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-parserIt 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-parserIt 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 typeparameters to Content-Typethe parsing method.

For example, you can use parsing on the text/plaincontent 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-parserModule API

After installing the module via npm install body-parsercommand, the module reference can be obtained by:

var bodyParser = require('body-parser')

bodyParserVariables are references to middleware. After the request body is parsed, the parsed value will be put into req.bodythe 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 jsonformatted data. This method supports arbitrary Unicode-encoded request bodies, and supports gzipand deflateencoded data compression.

Option is an object containing the following optional values

  • inflate - trueWhen set to , deflatecompressed data will be truedecompressed to , deflatecompressed data will be rejected. Default is true.
  • limit - Set the maximum amount of data requested. The default is'100kb'
  • reviverJSON.parse()- The second parameter  passed to the method, see JSON.parse() for details
  • strict - trueWhen set to, only two formats will be parsed Array; Objectset to falsewill parse all JSON.parsesupported 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 will fn(req)get the actual value through it. Default is application/json.
  • verify - This option is only verify(req, res, buf, encoding)supported when

 

2.2  bodyParser.raw() - Parsing binary format

bodyParser.raw(options)

BufferReturns a middleware that handles all data as a format. This method supports gzipand deflateencodes data compression. After parsing, all the req.bodyfollowing will be a Bufferdata.

Option is an object containing the following optional values

  • inflate - trueWhen set to , deflatecompressed data will be truedecompressed to , deflatecompressed data will be rejected. Default is true.
  • 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 will fn(req)get the actual value through it. Default is application/octet-stream.
  • verify - This option is only verify(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 gzipand deflateencodes data compression. After parsing, all following req.bodywill be a string value.

Option is an object containing the following optional values

  • defaultCharset - If Content-Typeno encoding is specified after, this encoding is used. The default is'utf-8'
  • inflate - trueWhen set to , deflatecompressed data will be truedecompressed to , deflatecompressed data will be rejected. Default is true.
  • 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 will fn(req)get the actual value through it. Default is application/octet-stream.
  • verify - This option is only verify(req, res, buf, encoding)supported when

 

2.4  bodyParser.urlencoded() - Parsing text format

bodyParser.urlencoded(options)

Returns a urlencodedmiddleware that handles data. This method uses UTF-8 encoding by default, and supports gzipand deflateencoded data compression. After parsing, all subsequent req.bodyentries will be a key-value object.

Option is an object containing the following optional values

  • extended - When falseset to , use the querystringtrue library to parse URL-encoded data; when set to , use qsthe library to parse URL-encoded data. When no encoding is specified after, this encoding is used. The default istrue
  • inflate - trueWhen set to , deflatecompressed data will be truedecompressed to , deflatecompressed data will be rejected. Default is true.
  • 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 will fn(req)get the actual value through it. Default is application/octet-stream.
  • verify - This option is only verify(req, res, buf, encoding)supported when

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325055937&siteId=291194637