Nodejs中Express 常用中介軟體 body-parser 實現解析,nodejsbody-parser

來源:互聯網
上載者:User

Nodejs中Express 常用中介軟體 body-parser 實現解析,nodejsbody-parser

寫在前面

body-parser是非常常用的一個express中介軟體,作用是對post請求的請求體進行解析。使用非常簡單,以下兩行代碼已經覆蓋了大部分的使用情境。

app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));

本文從簡單的例子出發,探究body-parser的內部實現。至於body-parser如何使用,感興趣的同學可以參考官方文檔。

入門基礎

在正式講解前,我們先來看一個POST請求的報文,如下所示。

POST /test HTTP/1.1Host: 127.0.0.1:3000Content-Type: text/plain; charset=utf8Content-Encoding: gzipchyingp

其中需要我們注意的有Content-TypeContent-Encoding以及報文主體:

  1. Content-Type:請求報文主體的類型、編碼。常見的類型有text/plain、application/json、application/x-www-form-urlencoded。常見的編碼有utf8、gbk等。
  2. Content-Encoding:聲明報文主體的壓縮格式,常見的取值有gzip、deflate、identity。
  3. 報文主體:這裡是個普通的文本字串chyingp。

body-parser主要做了什麼

body-parser實現的要點如下:

1.處理不同類型的請求體:比如text、json、urlencoded等,對應的報文主體的格式不同。

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

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

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

一、處理不同類型請求體

為了方便讀者測試,以下例子均包含服務端、用戶端代碼,完整代碼可在筆者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');

服務端代碼如下。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) );

服務端代碼如下,相比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() );  // 關鍵代碼      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) );

服務端代碼如下,同樣跟text/plain的解析差不多,就多了個querystring.parse()的調用。

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() ); // 關鍵代碼    res.end(`Your nick is ${body.nick}`)  });});server.listen(3000);

二、處理不同編碼

很多時候,來自用戶端的請求,採用的不一定是預設的utf8編碼,這個時候,就需要對請求體進行解碼處理。

用戶端請求如下,有兩個要點。

1.編碼聲明:在Content-Type最後加上;charset=gbk

2.請求體編碼:這裡藉助了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編碼,所以請求發送前,需要先進行編碼var buff = iconv.encode('程式猿小卡', encoding);var client = http.request(options, (res) => {  res.pipe(process.stdout);});client.end(buff, encoding);

服務端代碼如下,這裡多了兩個步驟:編碼判斷、解碼操作。首先通過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壓縮的例子。用戶端代碼如下,要點如下:

1.壓縮型別宣告:Content-Encoding賦值為gzip。

2.請求體壓縮:通過zlib模組對請求體進行gzip壓縮。

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 設定為 gzip 的同時,發送給服務端的資料也應該先進行gzipvar buff = zlib.gzipSync('chyingp');client.end(buff);

服務端代碼如下,這裡通過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;  // 關鍵代碼如下  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的核心實現並不複雜,翻看源碼後你會發現,更多的代碼是在處理異常跟邊界。

另外,對於POST請求,還有一個非常常見的Content-Typemultipart/form-data,這個的處理相對複雜些,body-parser不打算對其進行支援。篇幅有限,後續章節再繼續展開。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.