DIV CSS 佈局教程網

node-http-proxy 修改代理響應結果的實例代碼
編輯:關於JavaScript     

最近在項目中用到 node-http-proxy,遇到了需要修改代理服務器響應結果的需求。該庫官方提供了名為 Harmon 的方案來改寫 HTML 響應,但我們項目統一返回 JSON,用 Harmon 顯得有些笨重。於是便自己寫了一個可解析並修改 JSON 的輕量庫。這個過程中也踩到了兩個之前沒太留意的點:HTTP 傳輸編碼,以及 Node 流的相關處理。下面是實現思路與代碼。

 var zlib = require('zlib'); var concatStream = require('concat-stream'); /** * Modify the response of json * @param res {Response} The http response * @param contentEncoding {String} The http header content-encoding: gzip/deflate * @param callback {Function} Custom modified logic */ module.exports = function modifyResponse(res, contentEncoding, callback) { var unzip, zip; // Now only deal with the gzip and deflate content-encoding. if (contentEncoding === 'gzip') { unzip = zlib.Gunzip(); zip = zlib.Gzip(); } else if (contentEncoding === 'deflate') { unzip = zlib.Inflate(); zip = zlib.Deflate(); } // The cache response method can be called after the modification. var _write = res.write; var _end = res.end; if (unzip) { unzip.on('error', function (e) { console.log('Unzip error: ', e); _end.call(res); }); } else { console.log('Not supported content-encoding: ' + contentEncoding); return; } // The rewrite response method is replaced by unzip stream. res.write = function (data) { unzip.write(data); }; res.end = function (data) { unzip.end(data); }; // Concat the unzip stream. var concatWrite = concatStream(function (data) { var body; try { body = JSON.parse(data.toString()); } catch (e) { body = data.toString(); console.log('JSON.parse error:', e); } // Custom modified logic if (typeof callback === 'function') { body = callback(body); } // Converts the JSON to buffer. body = new Buffer(JSON.stringify(body)); // Call the response method and recover the content-encoding. zip.on('data', function (chunk) { _write.call(res, chunk); }); zip.on('end', function () { _end.call(res); }); zip.write(body); zip.end(); }); unzip.pipe(concatWrite); };

整體思路是:先根據響應頭的 content-encoding 建立對應的解壓與壓縮流(目前只處理 gzip 與 deflate),再把 res.write / res.end 改寫為寫入解壓流;隨後用 concat-stream 把解壓後的數據拼接完整,在回調中完成 JSON 解析與自定義修改,最後重新壓縮並寫回響應。

這個折騰的過程讓我更深刻地體會到理論知識的重要性——所謂理論是行動的先導。以前總是直接用第三方庫,很少去關心底層的細節處理,一旦遇到棘手問題就容易卡住。之後還是多花時間看看底層實現為好。希望這份實例對你有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved