Express middleware body-parser

Posted by HockeyDevil07 on Tue, 20 Aug 2019 05:07:54 +0200

Links to the original text: https://www.jianshu.com/p/cd3de110b4b6

Brief Introduction to Body Parser

In the http request type, POST, PUT and PATCH contain the request body, which is called request-body. In the original http module of Nodejs, the request body is accepted and parsed in a flow-based manner.

body-parser is an HTTP request body parsing middleware, which can be used to parse requests in JSON, Raw, text, and URL-encoded formats.

In Node's native http module, the user request data is encapsulated in req, an Incoming Message, which is also a readable stream object. When a native Http server or does not depend on a third-party parsing module, the request body can be requested and parsed in the following way:

    const http = require('http');

    http.createServer(function(req, res){
        if(req.method.toLowerCase() === 'post'){
            let body = '';
            //This step is to receive data
            req.on('data', function(chunk){
                body += chunk;
            });
            //Start parsing
            req.on('end', function(){
                if(req.headers['content-type'].indexOf('application/json')!==-1){
                    JSON.parse(body);
                }else if(req.headers['content-type'].indexOf('application/octet-stream')!==-1){
                    //Rwa 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 parsing
                }else{
                //Other format parsing
                }
            })
        }else{
            res.end('Other submissions')
        }
    }).listen(3000)

Express framework uses body-parser as the request body parsing middleware by default. After creating Express project, it can be found in app.js file:

/* Introducing dependencies */
var express = require('express');
// ......
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// ......

// Parsing application/json
app.use(bodyParser.json()); 
// Analysis of application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());

In this way, the body-parser module can be introduced to process the request body at the application level of the project. In the above code, the module handles request bodies in application/x-www-form-urlencoded and application/json formats. With this middleware, request parameters can be accessed in req.body of all routing processors.

In practical projects, different paths may require users to use different content types. body-parser also supports adding request body parsing for a single express route, such as:

var express = require('express');
var bodyParser = require('body-parser');

var app = new express();

//Create application/json parsing
var jsonParser = bodyParser.json();

//Create application/x-www-form-urlencoded
var urlencodedParser = bodyParser.urlencoded({extended: false});

//Request body for URL encoding in POST/login
app.post('/login', urlencodedParser, function(req, res){
    if(!req.body) return res.sendStatus(400);
    res.send('welcome, ' + req.body.username);
})

//POST/api/users to obtain 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 also supports specifying parsing methods for requesters of a particular content type or class of content types, which can be modified by adding type parameters to the parsing method.

For example, use JSON to parse text/plain content types:

app.use(bodyParser.json({type: 'text/plain'}))

This option is more used for parsing in non-standard request headers:

// Resolve custom JSON
app.use(bodyParser.json({ type: 'application/*+json' }))

// Resolve custom Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

// Processing HTML request bodies as strings
app.use(bodyParser.text({ type: 'text/html' }))

API of body-parser module

When the request body is parsed, the parsed value is placed in the req.body attribute, and when the content is empty, it is an empty object {}.

  • - body Parser. JSON () -- parsing JSON format
  • bodyParser.raw() -- parsing binary format
  • - body Parser. text () -- parsing text format
  • - body Parser. urlencoded () -- parsing text format

Topics: JSON encoding Attribute