麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > JavaScript > 正文

node-http-proxy修改響應結果實例代碼

2019-11-20 09:47:26
字體:
來源:轉載
供稿:網友

最近在項目中使用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修改響應結果實例代碼,希望對大家有所幫助!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 曰韩一级片 | 黄色网址免费进入 | 一区二区三区在线视频观看58 | 一级黄色在线观看 | av免费大全 | 小情侣嗯啊哦视频www | 成年人在线免费播放视频 | 青草久久网 | 日产精品久久久一区二区开放时间 | 久久久久国产精品久久久久 | 色人阁导航| 国产一区二区在线观看视频 | 色天使中文字幕 | 一级黄色免费观看视频 | 91精品国产综合久久男男 | 精品人伦一区二区三区蜜桃网站 | 久久综合婷婷 | 国产精品999在线观看 | 午夜精品福利视频 | 毛片免费视频播放 | 爱性久久久久久久 | 亚洲综合精品 | 日本欧美一区二区三区视频麻豆 | 国产妞干网 | 欧美乱码精品一区 | 欧美黄色大片免费观看 | 国产精品av久久久久久无 | 一区二区三区日韩电影 | h网站在线观看 | 日本中文视频 | 99精品在线观看 | 免费亚洲视频在线观看 | 国产午夜精品久久久久婷 | 国产分类视频 | 色七七网站 | 精品国产一区二区三区在线观看 | 国产视频在线一区 | 国产精品片一区二区三区 | 亚洲影视在线 | 欧美激情视频一区二区免费 | 久久成年网站 |