一、簡介
- github
- node.js body 解析中間件
- 處理程序之前,在中間件中對傳入的請求體進行解析(response body)
-
body-parser
提供四種解析器
JSON body parser
Raw body parser
Text body parser
URL-encoded form body parser
二、使用
搭建一個簡單的demo
mkdir body-parser-demo cd body-parser-demo npm init -y npm install express body-parser --save
新建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) })
執行node index.js,
網絡模擬請求使用Postman
工具
不使用中間件,直接獲取body為undefined
1、JSON解析器
app.post('/login.do', jsonParser, (req, res) => { console.log('********************') console.log(req.body) res.end(); })
注:如果在模擬器上以非JSON
格式發送,則會獲得一個空的JSON
對象
urlencoded解析器即將上述代碼的 jsonParser 換成 urlencodedParser
即可
2、加載到沒有掛載路徑的中間件
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false })) // parse application/json
app.use(bodyParser.json())