How to create a simple http proxy in node.js?

Salam (means hello) :)

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:

the following resource should be served:

here is what I came up with:


function onRequest (client_req, client_res) {
    client_req.addListener("end", function() {
        var options = {
            hostname: '',
            port: 80,
            path: client_req.url,
            method: 'GET'
        var req=http.request(options, function(res) {
            var body;
            res.on('data', function (chunk) {
                body += chunk;
            res.on('end', function () {
                 client_res.writeHead(200, { 'Content-Type': mime_of(client_req.url)});

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).

Leave a Reply

Your email address will not be published. Required fields are marked *