Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save gladiopeace/fb221ceae92523b19150eac8f2642ee5 to your computer and use it in GitHub Desktop.

Select an option

Save gladiopeace/fb221ceae92523b19150eac8f2642ee5 to your computer and use it in GitHub Desktop.

Revisions

  1. @amontalenti amontalenti created this gist Nov 21, 2012.
    46 changes: 46 additions & 0 deletions script-inject-http-proxy.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    var httpProxy = require('http-proxy');
    var url = require('url');

    httpProxy.createServer(function(req, res, proxy) {

    var isHtml = false,
    write = res.write,
    writeHead = res.writeHead,
    params = url.parse(req.url, true).query,
    dest = params.dest || 'localhost',
    destination;

    dest = dest.match(/^http/) ? dest : 'http://' + dest;
    destination = url.parse(dest, true);

    req.headers['host'] = destination.host;
    req.headers['url'] = destination.href;

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

    res.writeHead = function(code, headers) {
    isHtml = headers['content-type'] && headers['content-type'].match('text/html');
    writeHead.apply(this, arguments);
    }

    res.write = function(data, encoding) {
    if (isHtml && params.dest) {
    var str = data.toString();
    var scriptTag = '<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>';
    var baseTag = '<base href="' + (dest.replace(/\/$/, '') || '') + '"/>';

    str = str.replace(/(<head[^>]*>)/, "$1" + "\n" + scriptTag + "\n" + baseTag);

    data = new Buffer(str);
    }

    write.call(this, data, encoding);
    };

    proxy.proxyRequest(req, res, {
    host: destination.host,
    port: 80,
    });
    }).listen(9000, function () {
    console.log("Waiting for requests...");
    });