在http請求中,POST、PUT、PATCH三種請求方法中包含着請求體,也就是所謂的request,在Nodejs原生的http子產品中,請求體是要基于流的方式來接受和解析。
body-parser是一個HTTP請求體解析的中間件,使用這個子產品可以解析JSON、Raw、文本、URL-encoded格式的請求體,
Node原生的http子產品中,是将使用者請求資料封裝到了用于請求的對象req中,這個對象是一個IncomingMessage,該對象同時也是一個可讀流對象。在原生Http伺服器,或不依賴第三方解析子產品時,可以用下面的方法請求并且解析請求體
const http = require('http');
http.createServer(function(req, res){
if(req.method.toLowerCase() === 'post'){
let body = '';
//此步驟為接收資料
req.on('data', function(chunk){
body += chunk;
});
//開始解析
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格式請求體解析
}else if(req.headers['content-type'].indexOf('text/plain')!==-1){
//text文本格式請求體解析
}else if(req.headers['content-type'].indexOf('application/x-www-form-urlencoded')!==-1){
//url-encoded格式請求體解析
}else{
//其他格式解析
}
})
}else{
res.end('其他方式送出')
}
}).listen(3000)
Express架構預設使用body-parser作為請求體解析中間件,在建立了Express項目之後,可以在app.js檔案中找到
/* 引入依賴項 */
var express = require('express');
// ……
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// ……
// 解析 application/json
app.use(bodyParser.json());
// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());
這樣就可以在項目的application級别,引入了body-parser子產品處理請求體。在上述代碼中,子產品會處理application/x-www-form-urlencoded、application/json兩種格式的請求體。經過這個中間件後,就可以在所有路由處理器的req.body中通路請求參數
在實際項目中,不同路徑可能要求使用者使用不同的内容類型,body-parser還支援為單個express路由添加請求體解析,比如
var express = require('express');
var bodyParser = require('body-parser');
var app = new express();
//建立application/json解析
var jsonParser = bodyParser.json();
//建立application/x-www-form-urlencoded
var urlencodedParser = bodyParser.urlencoded({extended: false});
//POST /login 中擷取URL編碼的請求體
app.post('/login', urlencodedParser, function(req, res){
if(!req.body) return res.sendStatus(400);
res.send('welcome, ' + req.body.username);
})
//POST /api/users 擷取JSON編碼的請求體
app.post('/api/users', jsonParser, function(req,res){
if(!req.body) return res.sendStatus(400);
//create user in req.body
})
指定請求類型
body-parser還支援為某一種或者某一類内容類型的請求體指定解析方式,指定時可以通過在解析方法中添加type參數修改指定Content-Type的解析方式。
比如,對text/plain内容類型使用JSON解析
app.use(bodyParser.json({type: 'text/plain'}))
這一選項更多是用在非标準請求頭中的解析
// 解析自定義的 JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// 解析自定義的 Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// 将 HTML 請求體做為字元串處理
app.use(bodyParser.text({ type: 'text/html' }))
body-parser子產品的API
當請求體解析之後,解析值會被放到req.body屬性中,當内容為空時候,為一個空對象{}
---bodyParser.json()--解析JSON格式
---bodyParser.raw()--解析二進制格式
---bodyParser.text()--解析文本格式
---bodyParser.urlencoded()--解析文本格式