Skip to content
xna2 edited this page Jun 18, 2012 · 3 revisions

create a basic proxy server in nodejs

  1. create a proxy.js
var http = require('http');

var server = http.createServer();

server.on("request", function () {

    var proxyRequest = http.request({
        host:request.headers['host'],
        path:request.url(),
        method:request.method,
        headers: request.headers

    }, function(proxyResponse){
        reponse.writeHead(proxyResponse.statusCode, proxyResponse.headers);
        proxyResponse.pipe(response);
    });

    request.pipe(proxyRequest);

})


server.listen(8080);

  1. set your browser proxy to localhost and 8080 port

  2. proxyRequest.on("error",function(){ response.writeHead(500,{}

})

##make a proxy server that has error handleing and manipulate the data

var http = require('http');

var server = http.createServer();

server.on("request", function () {

    delete request.headers['accept-encoding'];

    var proxyRequest = http.request({
        host:request.headers['host'],
        path:request.url(),
        method:request.method,
        headers:request.headers

    }, function (proxyResponse) {
        reponse.writeHead(proxyResponse.statusCode, proxyResponse.headers);

        if (/text\/html/.exec(proxyResponse.headers['content-type'])) {

            console.log("Got HTML");
            var body = "";
            proxyResponse.on("data",
                function (chunk) {


                    body += chunk;


                }).on("end", function () {
                    body = body.replace(/Store/g, "Fag Shop");
                    response.end(body, "utf8");
                });
            {
            }
        }

        else {

            proxyResponse.pipe(response);
        }


    });

    //error handle
    proxyRequest.on('error', function () {

        response.writeHead(500, {
            "Content-Type":"text/plain"

        });

        response.end(request.url);

    })

});
Clone this wiki locally