详解用node.js实现简单的反向代理
之前用node.js实现简单的反向代理,最近需要回顾,就顺便发到随笔上了
不多说直接上代码!
consthttp=require('http');
consturl=require('url');
constquerystring=require('querystring');
http.createServer(function(oreq,ores){
console.log("服务已开启");
if(oreq){
if(oreq.url!=='/favicon.ico'){
letcontent='',
postData='';
//封装获取参数的方法
functiongetParmas(oUrl){
letoQuery=(typeofoUrl==="object")?oUrl:url.parse(oUrl,true).query,
data={};
for(iteminoQuery){
if(item!=='hostname'){
if(item!=='path'){
data[item]=oQuery[item];
}
}
}
returnquerystring.stringify(data);
};
//封装发起http请求的方法
functionhttpRequest(options,ores){
letdatas="";
returnhttp.request(options,function(res){
res.setEncoding('utf8');
res.on('data',function(chunk){
//返回数据
datas+=chunk;
});
res.on('end',function(){
ores.writeHead(200,{
"Content-Type":"application/json;charset=UTF-8",
"Access-Control-Allow-Origin":"*"
});
ores.end(datas);
})
})
};
//数据块接收中
console.log(oreq.method.toUpperCase());
if(oreq.method.toUpperCase()==="POST"){
console.log("进入POST");
oreq.on("data",function(postDataChunk){
postData+=postDataChunk;
});
//数据接收完毕,执行回调函数
oreq.on("end",function(){
console.log("接收完毕")
console.log(postData);
//配置options
letoData=JSON.parse(postData);
postData=getParmas(oData);
letoptions={
hostname:oData.hostname,
port:'80',
path:oData.path,
method:"POST"
};
//发送请求
letreq=httpRequest(options,ores);
req.on('error',function(e){
console.log('problemwithrequest:'+e.message);
});
req.write(postData);//发送请求数据
req.end();
});
}else{
letqueryObj=url.parse(oreq.url,true).query;
content=getParmas(oreq.url);
letoptions={
hostname:queryObj.hostname,
port:'80',
path:queryObj.path+content,
method:"GET"
};
//发送请求
letreq=httpRequest(options,ores);
req.on('error',function(e){
console.log('problemwithrequest:'+e.message);
});
req.end();
}
}
}
}).listen(8080,'127.0.0.1');
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。