node-http-proxy修改响应结果实例代码
最近在项目中使用node-http-proxy遇到需要修改代理服务器响应结果需求,该库已提供修改响应格式为html的方案:Harmon,而项目中返回格式统一为json,使用它感觉太笨重了,所以自己写了个可解析和修改json格式的库,
期间也遇到了之前未关注的问题:http传输编码、node流的相关处理。下面是实现代码:
varzlib=require('zlib');
varconcatStream=require('concat-stream');
/**
*Modifytheresponseofjson
*@paramres{Response}Thehttpresponse
*@paramcontentEncoding{String}Thehttpheadercontent-encoding:gzip/deflate
*@paramcallback{Function}Custommodifiedlogic
*/
module.exports=functionmodifyResponse(res,contentEncoding,callback){
varunzip,zip;
//Nowonlydealwiththegzipanddeflatecontent-encoding.
if(contentEncoding==='gzip'){
unzip=zlib.Gunzip();
zip=zlib.Gzip();
}elseif(contentEncoding==='deflate'){
unzip=zlib.Inflate();
zip=zlib.Deflate();
}
//Thecacheresponsemethodcanbecalledafterthemodification.
var_write=res.write;
var_end=res.end;
if(unzip){
unzip.on('error',function(e){
console.log('Unziperror:',e);
_end.call(res);
});
}else{
console.log('Notsupportedcontent-encoding:'+contentEncoding);
return;
}
//Therewriteresponsemethodisreplacedbyunzipstream.
res.write=function(data){
unzip.write(data);
};
res.end=function(data){
unzip.end(data);
};
//Concattheunzipstream.
varconcatWrite=concatStream(function(data){
varbody;
try{
body=JSON.parse(data.toString());
}catch(e){
body=data.toString();
console.log('JSON.parseerror:',e);
}
//Custommodifiedlogic
if(typeofcallback==='function'){
body=callback(body);
}
//ConvertstheJSONtobuffer.
body=newBuffer(JSON.stringify(body));
//Calltheresponsemethodandrecoverthecontent-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修改响应结果实例代码,希望对大家有所帮助!