【发布时间】:2013-12-19 12:55:57
【问题描述】:
我正在尝试创建一个代理服务器以将来自客户端的 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页面,但对于其他类型的文件,它只是返回一个空白页面或来自目标站点的一些错误消息(不同站点不同)。
【问题讨论】:
-
虽然答案使用
http,但相关模块从低抽象到高抽象的顺序是:node、http、connect、express取自stackoverflow.com/questions/6040012/…
标签: javascript node.js proxy