欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2016年06月06日 09:24:20   作者:阿郎博客  
這篇文章主要介紹了node-http-proxy修改響應(yīng)結(jié)果的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下

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

項(xiàng)目地址:node-http-proxy-json,歡迎大家試用提意見,同時(shí)不要吝嗇Star。

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

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

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

相關(guān)文章

最新評論