我正在尝试创建一个代理服务器,将HTTP GET
客户端的请求传递给第三方网站(比如google).我的代理只需要将传入的请求镜像到目标站点上的相应路径,因此如果我的客户端请求的URL是:
127.0.0.1/images/srpr/logo11w.png
应提供以下资源:
http://www.google.com/images/srpr/logo11w.png
这是我想出的:
http.createServer(onRequest).listen(80); function onRequest (client_req, client_res) { client_req.addListener("end", function() { var options = { hostname: 'www.google.com', port: 80, path: client_req.url, method: client_req.method headers: client_req.headers }; var req=http.request(options, function(res) { var body; res.on('data', function (chunk) { body += chunk; }); res.on('end', function () { client_res.writeHead(res.statusCode, res.headers); client_res.end(body); }); }); req.end(); }); }
它适用于html页面,但对于其他类型的文件,它只返回一个空白页面或来自目标站点的一些错误消息(在不同的站点中有所不同).
这是使用处理重定向的请求的代理服务器.通过点击您的代理URL http://domain.com:3000/?url=[your_url]来使用它
var http = require('http'); var url = require('url'); var request = require('request'); http.createServer(onRequest).listen(3000); function onRequest(req, res) { var queryData = url.parse(req.url, true).query; if (queryData.url) { request({ url: queryData.url }).on('error', function(e) { res.end(e); }).pipe(res); } else { res.end("no url found"); } }
我不认为处理从第三方服务器收到的响应是个好主意.这只会增加代理服务器的内存占用量.此外,这就是您的代码无法正常工作的原因.
而是尝试将响应传递给客户端.请考虑以下代码段:
var http = require('http'); http.createServer(onRequest).listen(3000); function onRequest(client_req, client_res) { console.log('serve: ' + client_req.url); var options = { hostname: 'www.google.com', port: 80, path: client_req.url, method: client_req.method, headers: client_req.headers }; var proxy = http.request(options, function (res) { client_res.writeHead(res.statusCode, res.headers) res.pipe(client_res, { end: true }); }); client_req.pipe(proxy, { end: true }); }
这是使用node-http-proxy
nodejitsu 的实现.
var http = require('http');
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({});
http.createServer(function(req, res) {
proxy.web(req, res, { target: 'http://www.google.com' });
}).listen(3000);