Express body-parser middleware

  • body-parser is used to parse HTTP request body intermediate can be resolved JSON, Raw, text, URL-encoded request body format;

  • Http module only native node, the third party does not rely on middleware, a method is available resolution request body:

    const http = require ( 'http'); http.createServer (function (req, res) {if (req.method.toLowerCase () === 'post') {let body = ''; // this step for receiving 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) {// raw format request body parsing} else if (req.headers [ 'content-type']. IndexOf ( 'text / plain')!-1) {// parse text body text request} else if (req.headers [ 'content-type']. IndexOf ( 'application / x-www-form-urlencoded')!-1) {// url-encoded format parsing the request body other formats} else {// parse}})} else {res.end ( 'otherwise submit')}}). Listen (3000)

  • Express default frame body-parser parses the request body as middleware, found in the file app.js var = bodyParser the require ( 'body-parser'); , thus can project in the application level, the introduction of body-parser module for processing request body. In a real project, the different paths may require the user to use different types of content, body-parser also express support for individual routing addition request parsing thereof, such as:

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

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

    //创建application/x-www-form-urlencoded var urlencodedParser = bodyParser.urlencoded();

    Get URL encoding // POST / login 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 acquired JSON-encoded request body app.post ( '/ api / users', jsonParser, function (req, res) {if (req.body) return res.sendStatus (400);! // create user in req.body})

  • Important: After API body-parser module body analytical When requested, the analytical value is placed req.body properties, when the time is empty, an empty subject --- bodyParser.json () - Parsing JSON format - --bodyParser.raw () - parsing binary format --- bodyParser.text () - parse text format --- bodyParser.urlencoded () - parse text format

Guess you like

Origin www.cnblogs.com/eslovez/p/12118973.html