How to use the http-proxy.createProxy function in http-proxy

To help you get started, we’ve selected a few http-proxy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github minetest-mapserver / minetest-tile-server / proxy.js View on Github external
const host = process.argv[2]; // host, for example: https://pandorabox.io/map
//TODO: argument parser, more options: port, debug,e etc

console.log("Creating proxy-connection for backend @ " + host);

var httpProxy = require('http-proxy'),
    http = require("http"),
    serveStatic = require('serve-static'),
    connect   = require('connect');


var proxy = httpProxy.createProxy({
	target: host,
	secure: false
});

var app = connect()
.use("/", function(req, res, next){
	if (req.url.substring(0,3) == "/js" || req.url == "/" || req.url.substring(0,5) == "/pics" || req.url == "/search.html" || req.url == "/index.html" || req.url.substring(0,4) == "/css"){
		console.log("Local: " + req.url);
		next();
		return;
	}

	console.log("Remote: " + req.url);
	proxy.web(req, res);
})
.use(serveStatic("src/main/resources/public"));
github sergiodxa / now-ab / index.js View on Github external
const { createServer } = require('http');
const { createProxy } = require('http-proxy');

const HOST = process.env.HOST || 'localhost';
const PORT = Number(process.env.PORT) || 3000;

// get the list of tes cases urls
const testCases = Object.entries(process.env)
  .filter(([key]) => key.startsWith('TEST_'))
  .reduce((acc, [key, value]) => {
    acc[key] = value;
    return acc;
  }, {});

// create a proxy
const proxy = createProxy({
  changeOrigin: true,
  target: {
    https: true
  }
});

// parse cookies from headers
const parseCookies = req => {
  const list = {};
  const rc = req.headers.cookie;

  rc &&
    rc.split(';').forEach(cookie => {
      const parts = cookie.split('=');
      list[parts.shift().trim()] = decodeURI(parts.join('='));
    });
github taylorhughes / skit / lib / SkitServer.js View on Github external
// 30-second default request duration.
  this.requestTimeout = options.requestTimeout || 30000;

  // Whether to handle redirects on the server side (loading the next
  // controller in the same request).
  this.enableServerSideRedirects = !!options.enableServerSideRedirects;

  this.logResourceRequests = !!options.logResourceRequests;
  this.logStaticRequests = !!options.logStaticRequests;

  this.redirectWithTrailingSlashes = !!options.redirectWithTrailingSlashes;

  this.notFoundProxy = null;
  if (options.notFoundProxy) {
    this.notFoundProxy = httpProxy.createProxy({target: options.notFoundProxy});
    this.notFoundProxy.on('error', function(err, req, res) {
      console.log('[skit not found proxy]', 'closing response due to error:', err);
      res.end();
    });
  }

  // Internal:

  this.urlArguments = {};
  if (options.urlArguments) {
    Object.keys(options.urlArguments).forEach(function(name) {
      this.registerUrlArgument(name, options.urlArguments[name]);
    }, this);
  }

  this.aliasMap = {};
github defunctzombie / zuul / lib / setup.js View on Github external
support_port = config.support_port = support_server.port;
        }

        // TODO start support server
        // currently happens within user_server

        var bouncer_port = 0;
        if (config.local && parseInt(config.local)) {
            bouncer_port = config.local;
        }

        if (config.phantom && parseInt(config.phantom)) {
            bouncer_port = config.phantom;
        }

        var proxy = httpProxy.createProxy();
        proxy.on('proxyReq', on_proxy_req);

        bouncer = http.createServer();
        bouncer.on('request', on_request(proxy.web));
        bouncer.on('upgrade', on_request(proxy.ws));

        function on_request(bounce) {
            return function(req, res) {
                var args = [].slice.call(arguments);
                if (is_control_req(req)) {
                    args.push({ target: 'http://' + loopback + ':' + control_port });
                    bounce.apply(proxy, args);
                    return;
                }

                args.push({ target: 'http://' + loopback + ':' + support_port }, on_support_server_proxy_done);
github h2non / rocky / lib / proxy.js View on Github external
module.exports = function createProxy(config) {
  var proxyOpts = _.clone(config)
  var proxy = httpProxy.createProxy(proxyOpts)

  proxy.on('proxyReq', onProxyRequest)
  proxy.on('error', onProxyError)

  return proxy

  function onProxyRequest(proxyReq, req, res, opts) {
    if (proxyReq.headersSent) { return } // Workaround, don't do this

    proxyReq.setHeader('X-Powered-By', 'rocky HTTP proxy')

    var protocol = req.headers['x-forwarded-proto'] || req.protocol
    if (protocol) proxyReq.setHeader('X-Forwarded-Proto', protocol)

    var host = req.headers['x-forwarded-host'] || req.headers.host
    if (host) proxyReq.setHeader('X-Forwarded-Host', host)
github airtap / airtap / lib / setup.js View on Github external
var loopback = opts.loopback || 'localhost'

    var supportPort
    if (supportServer) {
      supportPort = opts.support_port = supportServer.port
    }

    // TODO start support server
    // currently happens within userServer

    var bouncerPort = 0
    if (opts.local && parseInt(opts.local)) {
      bouncerPort = opts.local
    }

    var proxy = httpProxy.createProxy()
    proxy.on('proxyReq', onProxyRequest)

    bouncer = http.createServer()
    bouncer.on('request', onRequest(proxy.web))
    bouncer.on('upgrade', onRequest(proxy.ws))

    function localUrl (port, path) {
      var base = 'http://' + loopback + ':' + port
      return path ? base + path : base
    }

    function onRequest (bounce) {
      return function (req, res) {
        var args = [].slice.call(arguments)
        if (isControlRequest(req)) {
          args.push({ target: localUrl(opts.control_port) })
github godaddy / warehouse.ai / lib / app.js View on Github external
var App = module.exports = function App(root, options) {
  slay.App.call(this, root, options);

  this.env = process.env.NODE_ENV || 'development';
  this.after('close', this._onClose.bind(this));
  //
  // Setup our application proxy instance, mainly for making request
  // to our npm target.
  //
  // TODO: these options should be more configurable.
  //
  this.httpProxy = httpProxy.createProxy({
    changeOrigin: true,
    secure: false
  });

  this.agents = {};
};
github dimapaloskin / dev-gateway / lib / index.js View on Github external
rule.proc.stderr.unpipe(process.stderr);
        results.push(kill(rule.proc.pid, 'SIGINT'))
      }
    }

    await Promise.all(results);
    if (exitParent === undefined || exitParent !== false) {
      process.exit();
    }
  };

  exitHook(async () => {
    killChilds({});
  });

  const proxy = createProxy();
  const listener = createRequestListener(rules, options, proxy);
  const server = createServer(listener);

  options.port = options.port || 3000;
  server.listen(options.port, () => {
    console.log(`\n  Listen http://${options.host}:${options.port} \n`);
  });

  const promises = [];
  for (const rule of rules) {
    if (options.skip.length !== 0 && rule.slug && options.skip.includes(rule.slug)) {
      continue;
    }

    if (!rule.method) {
      rule.method = allHTTPMethods;
github OpenSOC / opensoc-ui / lib / modules / es-proxy.js View on Github external
exports = module.exports = function(config) {
  var httpProxy = require('http-proxy');
  var proxy = httpProxy.createProxy();

  proxy.on('error', function (err, req, res) {
    console.log("[proxyError]", err);
  });

  return function(req, res, next) {
    if (config.auth && !req.user) {
      res.send(403, 'Forbidden!');
      return;
    }

    delete req.headers.cookie;
    proxy.web(req, res, {
      target: config.elasticsearch.url
    });
  };
github altairstudios / nodeserver / nodeserver.js View on Github external
var httpProxy = require('http-proxy');
var http = require('http');
var https = require('https');
var agent = new http.Agent({ maxSockets: Number.MAX_VALUE });
var proxy = httpProxy.createProxy({ xfwd: true, agent: agent });
var fs = require('fs');
var nodeserverAdmin = require('./admin');
var os = require('os');
require('colors');
var core = require('./core');
var crypto = require('crypto');
var tls = require('tls');
var path = require('path');



module.exports = exports = function(inTerminal) {
	var self = this;
	this.websites = [];
	this.ports = [];
	this.securePorts = [];