国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

node-http-proxy修改響應(yīng)結(jié)果實(shí)例代碼

2019-11-20 09:47:26
字體:
供稿:網(wǎng)友

最近在項目中使用node-http-proxy遇到需要修改代理服務(wù)器響應(yīng)結(jié)果需求,該庫已提供修改響應(yīng)格式為html的方案:Harmon,而項目中返回格式統(tǒng)一為json,使用它感覺太笨重了,所以自己寫了個可解析和修改json格式的庫,

期間也遇到了之前未關(guān)注的問題:http傳輸編碼、node流的相關(guān)處理。下面是實(shí)現(xiàn)代碼:

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。

在該庫的實(shí)現(xiàn)過程中越發(fā)覺得理論知識的重要性,所謂理論是行動的先導(dǎo),之前都是使用第三方庫,也沒去關(guān)心一些底層的細(xì)節(jié)處理。

后面有空一定要多看看底層的實(shí)現(xiàn),否則遇到難搞問題就卡住了。

以上所述是小編給大家介紹的node-http-proxy修改響應(yīng)結(jié)果實(shí)例代碼,希望對大家有所幫助!

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 册亨县| 绍兴市| 桦甸市| 莒南县| 陆河县| 松滋市| 宜川县| 富民县| 浦东新区| 东丰县| 横峰县| 太仆寺旗| 宜昌市| 泰兴市| 威海市| 炎陵县| 达州市| 保山市| 邓州市| 赣榆县| 县级市| 恭城| 阆中市| 绿春县| 松原市| 元朗区| 宁国市| 沁水县| 永春县| 宜黄县| 新丰县| 巴塘县| 昌邑市| 濮阳市| 陆川县| 台前县| 札达县| 莱芜市| 泸州市| 平安县| 沧州市|