技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機(jī)純凈版,64位旗艦版,綠色軟件,免費(fèi)軟件下載基地!

當(dāng)前位置:主頁 > 教程 > 服務(wù)器類 >

Nodejs中Express 常用中間件 body-parser 實(shí)現(xiàn)代碼

來源:技術(shù)員聯(lián)盟┆發(fā)布時(shí)間:2017-10-13 00:29┆點(diǎn)擊:

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é)可以參考官方文檔。

入門基礎(chǔ)

在正式講解前,我們先來看一個(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)文主體:

Content-Type:請(qǐng)求報(bào)文主體的類型、編碼。常見的類型有text/plain、application/json、application/x-www-form-urlencoded。常見的編碼有utf8、gbk等。

Content-Encoding:聲明報(bào)文主體的壓縮格式,常見的取值有g(shù)zip、deflate、identity。

報(bào)文主體:這里是個(gè)普通的文本字符串chyingp。

body-parser主要做了什么

body-parser實(shí)現(xiàn)的要點(diǎn)如下:

1.處理不同類型的請(qǐng)求體:比如text、json、urlencoded等,對(duì)應(yīng)的報(bào)文主體的格式不同。

2.處理不同的編碼:比如utf8、gbk等。

3.處理不同的壓縮類型:比如gzip、deflare等。

4.其他邊界、異常的處理。

一、處理不同類型請(qǐng)求體

為了方便讀者測(cè)試,以下例子均包含服務(wù)端、客戶端代碼,完整代碼可在筆者github上找到。

解析text/plain

客戶端請(qǐng)求的代碼如下,采用默認(rèn)編碼,不對(duì)請(qǐng)求體進(jìn)行壓縮。請(qǐng)求體類型為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類型處理比較簡(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()的過程。

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對(duì)請(qǐng)求體進(jìn)行格式化,得到類似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í)候,來自客戶端的請(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)