寫在前面
body-parser
是非常常用的一個express
中間件,作用是對http請求體進行解析郊霎。使用非常簡單钉汗,以下兩行代碼已經(jīng)覆蓋了大部分的使用場景。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
本文從簡單的例子出發(fā)傻谁,探究body-parser
的內(nèi)部實現(xiàn)孝治。至于body-parser
如何使用,感興趣的同學(xué)可以參考官方文檔审磁。
入門基礎(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:聲明報文主體的壓縮格式疹瘦,常見的取值有
gzip
祠斧、deflate
、identity
拱礁。 - 報文主體:這里是個普通的文本字符串
chyingp
琢锋。
body-parser主要做了什么
body-parser
實現(xiàn)的要點如下:
- 處理不同類型的請求體:比如
text
、json
呢灶、urlencoded
等吴超,對應(yīng)的報文主體的格式不同。 - 處理不同的編碼:比如
utf8
鸯乃、gbk
等鲸阻。 - 處理不同的壓縮類型:比如
gzip
、deflare
等缨睡。 - 其他邊界鸟悴、異常的處理。
一奖年、處理不同類型請求體
為了方便讀者測試细诸,以下例子均包含服務(wù)端、客戶端代碼陋守,完整代碼可在筆者github上找到震贵。
解析text/plain
客戶端請求的代碼如下利赋,采用默認(rèn)編碼,不對請求體進行壓縮猩系。請求體類型為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);
二、處理不同編碼
很多時候硼补,來自客戶端的請求驮肉,采用的不一定是默認(rèn)的utf8
編碼,這個時候已骇,就需要對請求體進行解碼處理离钝。
客戶端請求如下,有兩個要點褪储。
- 編碼聲明:在
Content-Type
最后加上;charset=gbk
- 請求體編碼:這里借助了
iconv-lite
卵渴,對請求體進行編碼iconv.encode('程序猿小卡', encoding)
var http = require('http');
var iconv = require('iconv-lite');
var encoding = 'gbk'; // 請求編碼
var options = {
hostname: '127.0.0.1',
port: '3000',
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'text/plain; charset=' + encoding,
'Content-Encoding': 'identity',
}
};
// 備注:nodejs本身不支持gbk編碼,所以請求發(fā)送前鲤竹,需要先進行編碼
var buff = iconv.encode('程序猿小卡', encoding);
var client = http.request(options, (res) => {
res.pipe(process.stdout);
});
client.end(buff, encoding);
服務(wù)端代碼如下浪读,這里多了兩個步驟:編碼判斷、解碼操作辛藻。首先通過Content-Type
獲取編碼類型gbk
碘橘,然后通過iconv-lite
進行反向解碼操作。
var http = require('http');
var contentType = require('content-type');
var iconv = require('iconv-lite');
var parsePostBody = function (req, done) {
var obj = contentType.parse(req.headers['content-type']);
var charset = obj.parameters.charset; // 編碼判斷:這里獲取到的值是 'gbk'
var arr = [];
var chunks;
req.on('data', buff => {
arr.push(buff);
});
req.on('end', () => {
chunks = Buffer.concat(arr);
var body = iconv.decode(chunks, charset); // 解碼操作
done(body);
});
};
var server = http.createServer(function (req, res) {
parsePostBody(req, (body) => {
res.end(`Your nick is ${body}`)
});
});
server.listen(3000);
三吱肌、處理不同壓縮類型
這里舉個gzip
壓縮的例子痘拆。客戶端代碼如下氮墨,要點如下:
- 壓縮類型聲明:
Content-Encoding
賦值為gzip
错负。 - 請求體壓縮:通過
zlib
模塊對請求體進行g(shù)zip壓縮坟瓢。
var http = require('http');
var zlib = require('zlib');
var options = {
hostname: '127.0.0.1',
port: '3000',
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'Content-Encoding': 'gzip'
}
};
var client = http.request(options, (res) => {
res.pipe(process.stdout);
});
// 注意:將 Content-Encoding 設(shè)置為 gzip 的同時,發(fā)送給服務(wù)端的數(shù)據(jù)也應(yīng)該先進行g(shù)zip
var buff = zlib.gzipSync('chyingp');
client.end(buff);
服務(wù)端代碼如下犹撒,這里通過zlib
模塊折联,對請求體進行了解壓縮操作(guzip)。
var http = require('http');
var zlib = require('zlib');
var parsePostBody = function (req, done) {
var length = req.headers['content-length'] - 0;
var contentEncoding = req.headers['content-encoding'];
var stream = req;
// 關(guān)鍵代碼如下
if(contentEncoding === 'gzip') {
stream = zlib.createGunzip();
req.pipe(stream);
}
var arr = [];
var chunks;
stream.on('data', buff => {
arr.push(buff);
});
stream.on('end', () => {
chunks = Buffer.concat(arr);
done(chunks);
});
stream.on('error', error => console.error(error.message));
};
var server = http.createServer(function (req, res) {
parsePostBody(req, (chunks) => {
var body = chunks.toString();
res.end(`Your nick is ${body}`)
});
});
server.listen(3000);
寫在后面
body-parser
的核心實現(xiàn)并不復(fù)雜识颊,翻看源碼后你會發(fā)現(xiàn)诚镰,更多的代碼是在處理異常跟邊界。
另外祥款,對于POST請求清笨,還有一個非常常見的Content-Type
是multipart/form-data
,這個的處理相對復(fù)雜些刃跛,body-parser
不打算對其進行支持抠艾。篇幅有限,后續(xù)章節(jié)再繼續(xù)展開桨昙。
歡迎交流检号,如有錯漏請指出。