一转锈、簡(jiǎn)介
- github
- node.js body 解析中間件
- 處理程序之前脏嚷,在中間件中對(duì)傳入的請(qǐng)求體進(jìn)行解析(response body)
-
body-parser
提供四種解析器
JSON body parser
Raw body parser
Text body parser
URL-encoded form body parser
二祭往、使用
搭建一個(gè)簡(jiǎn)單的demo
mkdir body-parser-demo
cd body-parser-demo
npm init -y
npm install express body-parser --save
在根目錄下創(chuàng)建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)
})
執(zhí)行node index.js
網(wǎng)絡(luò)模擬請(qǐng)求使用Postman
工具
不使用中間件,直接獲取body
執(zhí)行結(jié)果:
undefined
JSON解析器
app.post('/login.do', jsonParser, (req, res) => {
console.log('********************')
console.log(req.body)
res.end();
})
Postman 以raw 方式發(fā)送JSON 數(shù)據(jù)冻记,執(zhí)行結(jié)果:
{ name: 'wang', password: '123456' }
注:如果在模擬器上以非JSON
格式發(fā)送济丘,則會(huì)獲得一個(gè)空的JSON
對(duì)象
urlencoded解析器
app.post('/login.do', urlencodedParser, (req, res) => {
console.log('********************')
console.log(req.body)
res.end();
})
執(zhí)行結(jié)果:
{ name: 'wang', password: '123456' }
加載到?jīng)]有掛載路徑的中間件
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
具體詳見(jiàn)GitHub README.md
注:注意為方便測(cè)試,請(qǐng)求處理時(shí)直接使用end()
生巡,否則會(huì)掛起