title: How to create a simple http proxy in node.js?
body: <p>I'm trying to create a proxy server to pass <code>HTTP GET</code> 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:</p>
  
  <pre><code>127.0.0.1/images/srpr/logo11w.png
  </code></pre>
  
  <p>The following resource should be served:</p>
  
  <pre><code>http://www.google.com/images/srpr/logo11w.png
  </code></pre>
  
  <p>Here is what I came up with:</p>
  
  <pre><code>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();
      });
  }
  </code></pre>
  
  <p>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).</p>