您好,登錄后才能下訂單哦!
寫(xiě)在前面
body-parser
是非常常用的一個(gè)express
中間件,作用是對(duì)post請(qǐng)求的請(qǐng)求體進(jìn)行解析。使用非常簡(jiǎn)單,以下兩行代碼已經(jīng)覆蓋了大部分的使用場(chǎng)景。
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
本文從簡(jiǎn)單的例子出發(fā),探究body-parser
的內(nèi)部實(shí)現(xiàn)。至于body-parser
如何使用,感興趣的同學(xué)可以參考官方文檔。
入門(mén)基礎(chǔ)
在正式講解前,我們先來(lái)看一個(gè)POST請(qǐng)求的報(bào)文,如下所示。
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
以及報(bào)文主體:
body-parser主要做了什么
body-parser
實(shí)現(xiàn)的要點(diǎn)如下:
1.處理不同類(lèi)型的請(qǐng)求體:比如text、json、urlencoded等,對(duì)應(yīng)的報(bào)文主體的格式不同。
2.處理不同的編碼:比如utf8、gbk等。
3.處理不同的壓縮類(lèi)型:比如gzip、deflare等。
4.其他邊界、異常的處理。
一、處理不同類(lèi)型請(qǐng)求體
為了方便讀者測(cè)試,以下例子均包含服務(wù)端、客戶端代碼,完整代碼可在筆者github上找到。
解析text/plain
客戶端請(qǐng)求的代碼如下,采用默認(rèn)編碼,不對(duì)請(qǐng)求體進(jìn)行壓縮。請(qǐng)求體類(lèi)型為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
類(lèi)型處理比較簡(jiǎn)單,就是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
,只是多了個(gè)JSON.parse()
的過(guò)程。
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
客戶端代碼如下,這里通過(guò)querystring
對(duì)請(qǐng)求體進(jìn)行格式化,得到類(lèi)似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
的解析差不多,就多了個(gè)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);
二、處理不同編碼
很多時(shí)候,來(lái)自客戶端的請(qǐng)求,采用的不一定是默認(rèn)的utf8
編碼,這個(gè)時(shí)候,就需要對(duì)請(qǐng)求體進(jìn)行解碼處理。
客戶端請(qǐng)求如下,有兩個(gè)要點(diǎn)。
1.編碼聲明:在Content-Type最后加上;charset=gbk
2.請(qǐng)求體編碼:這里借助了iconv-lite,對(duì)請(qǐng)求體進(jìn)行編碼iconv.encode('程序猿小卡', encoding)
var http = require('http'); var iconv = require('iconv-lite'); var encoding = 'gbk'; // 請(qǐng)求編碼 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編碼,所以請(qǐng)求發(fā)送前,需要先進(jìn)行編碼 var buff = iconv.encode('程序猿小卡', encoding); var client = http.request(options, (res) => { res.pipe(process.stdout); }); client.end(buff, encoding);
服務(wù)端代碼如下,這里多了兩個(gè)步驟:編碼判斷、解碼操作。首先通過(guò)Content-Type
獲取編碼類(lèi)型gbk
,然后通過(guò)iconv-lite
進(jìn)行反向解碼操作。
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);
三、處理不同壓縮類(lèi)型
這里舉個(gè)gzip
壓縮的例子??蛻舳舜a如下,要點(diǎn)如下:
1.壓縮類(lèi)型聲明:Content-Encoding賦值為gzip。
2.請(qǐng)求體壓縮:通過(guò)zlib模塊對(duì)請(qǐng)求體進(jìn)行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 的同時(shí),發(fā)送給服務(wù)端的數(shù)據(jù)也應(yīng)該先進(jìn)行g(shù)zip var buff = zlib.gzipSync('chyingp'); client.end(buff);
服務(wù)端代碼如下,這里通過(guò)zlib
模塊,對(duì)請(qǐng)求體進(jìn)行了解壓縮操作(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);
寫(xiě)在后面
body-parser
的核心實(shí)現(xiàn)并不復(fù)雜,翻看源碼后你會(huì)發(fā)現(xiàn),更多的代碼是在處理異常跟邊界。
另外,對(duì)于POST請(qǐng)求,還有一個(gè)非常常見(jiàn)的Content-Type
是multipart/form-data
,這個(gè)的處理相對(duì)復(fù)雜些,body-parser
不打算對(duì)其進(jìn)行支持。篇幅有限,后續(xù)章節(jié)再繼續(xù)展開(kāi)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。