最近在項目中使用node-http-proxy遇到需要修改代理服務器響應結果需求,該庫已提供修改響應格式為html的方案:Harmon,而項目中返回格式統一為json,使用它感覺太笨重了,所以自己寫了個可解析和修改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 logicif (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);};
項目地址:node-http-proxy-json,歡迎大家試用提意見,同時不要吝嗇Star。
在該庫的實現過程中越發覺得理論知識的重要性,所謂理論是行動的先導,之前都是使用第三方庫,也沒去關心一些底層的細節處理。
后面有空一定要多看看底層的實現,否則遇到難搞問題就卡住了。
以上所述是小編給大家介紹的node-http-proxy修改響應結果實例代碼,希望對大家有所幫助!
新聞熱點
疑難解答