body-parser是非常常用的一個express中間件,作用是對post請求的請求體進行解析。使用非常簡單,以下兩行代碼已經(jīng)覆蓋了大部分的使用場景。
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
本文從簡單的例子出發(fā),探究body-parser的內(nèi)部實現(xiàn)。至于body-parser如何使用,感興趣的同學可以參考官方文檔。
入門基礎(chǔ)
在正式講解前,我們先來看一個POST請求的報文,如下所示。
POST /test HTTP/1.1 Host: 127.0.0.1:3000 Content-Type: text/plain; charset=utf8 Content-Encoding: gzip chyingp
其中需要我們注意的有Content-Type、Content-Encoding以及報文主體:
Content-Type:請求報文主體的類型、編碼。常見的類型有text/plain、application/json、application/x-www-form-urlencoded。常見的編碼有utf8、gbk等。
Content-Encoding:聲明報文主體的壓縮格式,常見的取值有g(shù)zip、deflate、identity。
報文主體:這里是個普通的文本字符串chyingp。
body-parser主要做了什么
body-parser實現(xiàn)的要點如下:
1.處理不同類型的請求體:比如text、json、urlencoded等,對應的報文主體的格式不同。
2.處理不同的編碼:比如utf8、gbk等。
3.處理不同的壓縮類型:比如gzip、deflare等。
4.其他邊界、異常的處理。
一、處理不同類型請求體
為了方便讀者測試,以下例子均包含服務(wù)端、客戶端代碼,完整代碼可在筆者github上找到。
解析text/plain
客戶端請求的代碼如下,采用默認編碼,不對請求體進行壓縮。請求體類型為text/plain。
var http = require('http'); var options = { hostname: '127.0.0.1', port: '3000', path: '/test', method: 'POST', headers: { 'Content-Type': 'text/plain', 'Content-Encoding': 'identity' } }; var client = http.request(options, (res) => { res.pipe(process.stdout); }); client.end('chyingp');
服務(wù)端代碼如下。text/plain類型處理比較簡單,就是buffer的拼接。
var http = require('http'); var parsePostBody = function (req, done) { var arr = []; var chunks; req.on('data', buff => { arr.push(buff); }); req.on('end', () => { chunks = Buffer.concat(arr); done(chunks); }); }; var server = http.createServer(function (req, res) { parsePostBody(req, (chunks) => { var body = chunks.toString(); res.end(`Your nick is ${body}`) }); }); server.listen(3000);
解析application/json
客戶端代碼如下,把Content-Type換成application/json。
var http = require('http'); var querystring = require('querystring'); var options = { hostname: '127.0.0.1', port: '3000', path: '/test', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Encoding': 'identity' } }; var jsonBody = { nick: 'chyingp' }; var client = http.request(options, (res) => { res.pipe(process.stdout); }); client.end( JSON.stringify(jsonBody) );
服務(wù)端代碼如下,相比text/plain,只是多了個JSON.parse()的過程。
var http = require('http'); var parsePostBody = function (req, done) { var length = req.headers['content-length'] - 0; var arr = []; var chunks; req.on('data', buff => { arr.push(buff); }); req.on('end', () => { chunks = Buffer.concat(arr); done(chunks); }); }; var server = http.createServer(function (req, res) { parsePostBody(req, (chunks) => { var json = JSON.parse( chunks.toString() ); // 關(guān)鍵代碼 res.end(`Your nick is ${json.nick}`) }); }); server.listen(3000);
解析application/x-www-form-urlencoded
客戶端代碼如下,這里通過querystring對請求體進行格式化,得到類似nick=chyingp的字符串。
var http = require('http'); var querystring = require('querystring'); var options = { hostname: '127.0.0.1', port: '3000', path: '/test', method: 'POST', headers: { 'Content-Type': 'form/x-www-form-urlencoded', 'Content-Encoding': 'identity' } }; var postBody = { nick: 'chyingp' }; var client = http.request(options, (res) => { res.pipe(process.stdout); }); client.end( querystring.stringify(postBody) );
服務(wù)端代碼如下,同樣跟text/plain的解析差不多,就多了個querystring.parse()的調(diào)用。
var http = require('http'); var querystring = require('querystring'); var parsePostBody = function (req, done) { var length = req.headers['content-length'] - 0; var arr = []; var chunks; req.on('data', buff => { arr.push(buff); }); req.on('end', () => { chunks = Buffer.concat(arr); done(chunks); }); }; var server = http.createServer(function (req, res) { parsePostBody(req, (chunks) => { var body = querystring.parse( chunks.toString() ); // 關(guān)鍵代碼 res.end(`Your nick is ${body.nick}`) }); }); server.listen(3000);
二、處理不同編碼
很多時候,來自客戶端的請求,采用的不一定是默認的utf8編碼,這個時候,就需要對請求體進行解碼處理。
客戶端請求如下,有兩個要點。
1.編碼聲明:在Content-Type最后加上;charset=gbk
2.請求體編碼:這里借助了iconv-lite,對請求體進行編碼iconv.encode('程序猿小卡', encoding)