如何在node.js中创建一个简单的http代理?

如何在node.js中创建一个简单的http代理?

问题描述:

我正在尝试创建一个代理服务器,将客户端的 HTTP GET 请求传递给第三方网站(比如google)。我的代理只需要将传入的请求镜像到目标站点上的相应路径,所以如果我的客户端请求的URL是:

I'm trying to create a proxy server to pass HTTP GET requests from a client to a third party website (say google). My proxy just needs to mirror incoming requests to their corresponding path on the target site, so if my client's requested url is:

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页面,但对于其他类型的文件,它只是从目标站点返回一个空白页面或一些错误消息(在不同的站点中有所不同)。

it works well with html pages, but for other types of files, it just returns a blank page or some error message from target site (which varies in different sites).

我不认为这是处理从第三方服务器收到的响应的好主意。这只会增加代理服务器的内存占用量。此外,这就是您的代码无法正常工作的原因。

I don't think it's a good idea to process response received from the 3rd party server. This will only increase your proxy server's memory footprint. Further, it's the reason why your code is not working.

而是尝试将响应传递给客户端。请考虑以下代码段:

Instead try passing the response through to the client. Consider following snippet:

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
  });
}