I. Introduction
- github
- node.js body analytic middleware
- Before processing program, in the middleware parsing (response body) of the incoming request body
-
body-parser
Offers four parser JSON body Parser Raw body Parser Text Parser body the URL of body-encoded form Parser
Second, the use
Build a simple demo
mkdir body-parser-demo
cd body-parser-demo
npm init -y
npm install express body-parser --save
New index.js
var express = require('express')
var bodyParser = require('body-parser')
const localPort = 3000
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/login.do', (req, res) => {
console.log('********************')
console.log(req.body)
res.end();
})
app.listen(localPort, () => {
console.log('http://127.0.0.1:%s', host, port)
})
Perform node index.js,
network simulation request to use Postman
tools
Do not use middleware, direct accessbody为undefined
1, JSON parser
app.post('/login.do', jsonParser, (req, res) => {
console.log('********************')
console.log(req.body)
res.end();
})
NOTE: If the simulator non JSON
format transmission, will obtain an empty JSON
target
urlencoded解析器即将上述代码的 jsonParser 换成 urlencodedParser
即可
2、加载到没有挂载路径的中间件
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())