最近在项目中使用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 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);
};
项目地址:node-http-proxy-json,欢迎大家试用提意见,同时不要吝啬Star。
在该库的实现过程中越发觉得理论知识的重要性,所谓理论是行动的先导,之前都是使用第三方库,也没去关心一些底层的细节处理。
后面有空一定要多看看底层的实现,否则遇到难搞问题就卡住了。
以上所述是小编给大家介绍的node-http-proxy修改响应结果实例代码,希望对大家有所帮助!
标签:
node,http,proxy
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“node-http-proxy修改响应结果实例代码”评论...
更新日志
2025年10月29日
2025年10月29日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]