一、概念
正向代理:代理client,用于代理上网
反向代理:代理server,用于网站防护、负载均衡
二、实现
NodeJs代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| var http = require("http"); var url = require("url");
http.createServer(function(req,res){ console.log("start request:",req.url);
var option = url.parse(req.url); option.headers = req.headers;
var proxyRequest = http.request(option, function(proxyResponse){
proxyResponse.on("data",function(chunk){ console.log("proxyResponse length",chunk.length); }); proxyResponse.on("end",function(){ console.log("proxyed request ended"); res.end(); })
res.writeHead(proxyResponse.statusCode,proxyResponse.headers); });
req.on("data",function(chunk){ console.log("in request length:",chunk.length); proxyRequest.write(chunk,"binary"); })
req.on("end",function(){ console.log("original request ended"); proxyRequest.end(); })
}).listen(8080);
|
三、测试
- 启动Node服务器
- 设置浏览器的http代理
- 打开网页,正常,测试成功
参考:《Node.JS实战17:开发一个正向代理服务器》