国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 天柱县| 财经| 左权县| 彭山县| 阳西县| 乌鲁木齐市| 长垣县| 北川| 浦北县| 马山县| 皮山县| 婺源县| 武山县| 石首市| 明溪县| 望江县| 西青区| 营山县| 宣汉县| 改则县| 洪江市| 安龙县| 丹东市| 临夏市| 河北省| 泾源县| 宁晋县| 霍州市| 太和县| 镶黄旗| 河东区| 榆社县| 易门县| 定安县| 沛县| 岑巩县| 丽江市| 阿瓦提县| 茌平县| 阆中市| 三门峡市|