How to use the http-proxy.createProxyServer 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 beakerbrowser / homebase / lib / vhosts / proxy.js View on Github external
const express = require('express')
const chalk = require('chalk')
const proxy = require('http-proxy').createProxyServer()

module.exports.start = function (vhostCfg, config) {
  var server = express()

  server.all('*', function (req, res) {
    proxy.web(req, res, {target: vhostCfg.to})
  })

  // log
  console.log(`${chalk.bold(`Proxying`)} ${chalk.dim(`from`)} ${vhostCfg.from} ${chalk.dim(`to`)} ${vhostCfg.to}`)

  return server
}

module.exports.stop = function (vhostCfg) {
  // log
github jupyterhub / jupyterhub / lib / configproxy.js View on Github external
var ConfigurableProxy = function (options) {
    var that = this;
    this.options = options || {};
    this.auth_token = this.options.auth_token;
    this.upstream_ip = this.options.upstream_ip || 'localhost';
    this.upstream_port = this.options.upstream_port || 8081;
    
    this.default_target = "http://" + this.upstream_ip + ":" + this.upstream_port;
    this.routes = {};
    
    var proxy = this.proxy = httpProxy.createProxyServer({
        ws : true
    });
    // tornado-style regex routing,
    // because cross-language cargo-culting is always a good idea
    
    this.api_handlers = [
        [ /^\/api\/routes$/, {
            get : bound(this, authorized(this.get_routes))
        } ],
        [ /^\/api\/routes(\/.*)$/, {
            post : json_handler(bound(this, authorized(this.post_routes))),
            'delete' : bound(this, authorized(this.delete_routes))
        } ]
    ];
    
    var log_errors = function(handler) {
github caprover / caprover / app-backend / built / app.js View on Github external
const favicon = require("serve-favicon");
const logger = require("morgan");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const httpProxyImport = require("http-proxy");
const CaptainManager = require("./user/system/CaptainManager");
const BaseApi = require("./api/BaseApi");
const ApiStatusCodes = require("./api/ApiStatusCodes");
const Injector = require("./injection/Injector");
const Logger = require("./utils/Logger");
const CaptainConstants = require("./utils/CaptainConstants");
const LoginRouter = require("./routes/LoginRouter");
const UserRouter = require("./routes/UserRouter");
const InjectionExtractor = require("./injection/InjectionExtractor");
// import { NextFunction, Request, Response } from 'express'
const httpProxy = httpProxyImport.createProxyServer({});
let app = express();
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, '../public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false,
}));
app.use(cookieParser());
if (CaptainConstants.isDebug) {
    app.use('*', function (req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Credentials', 'true');
        res.setHeader('Access-Control-Allow-Headers', CaptainConstants.headerNamespace +
            ',' +
github opencord / xos / views / ngXosViews / hpc / gulp / server.js View on Github external
var path = require('path');

const environment = process.env.NODE_ENV;

if(!fs.existsSync(path.join(__dirname, `../../../env/${environment || 'default'}.js`))){
  if(!environment){
    throw new Error('You should define a default.js config in /views/env folder.');
  }
  else{
    throw new Error(`Since you are loading a custom environment, you should define a ${environment}.js config in /views/env folder.`);
  }
}

var conf = require(path.join(__dirname, `../../../env/${environment || 'default'}.js`));

var proxy = httpProxy.createProxyServer({
  target: conf.host
});


proxy.on('error', function(error, req, res) {
  res.writeHead(500, {
    'Content-Type': 'text/plain'
  });

  console.error('[Proxy]', error);
});

module.exports = function(options){

  gulp.task('browser', function() {
    browserSync.init({
github QUANTAXIS / QUANTAXIS / proxy.js View on Github external
var proxy = require('http-proxy').createProxyServer({
  target: {host: '192.168.4.198', port: 8080}
}).on('error', function(err, req, res) {
  console.log('[ERROR] %s', err);
  res.end();
});
var server = require('http').createServer(function(req, res) {
  console.log('[REQUEST.%s] %s', req.method, req.url);
  console.log(req['headers']);
  if (req.method == 'POST') {
    var body = '';
    req.on('data', function (data) {
      body += data;
    });
    req.on('end', function () {
      print_body('[REQUEST.BODY] ', body);
    });
github Irrelon / node-irrelon-router / router.js View on Github external
honorCipherOrder: true,
		secureOptions: sslConfig.minimumTLSVersion
	}, function (req, res) {
		self.handleRequest.call(self, true, req, res);
	});

	self.httpServer = http.createServer(function (req, res) {
		self.handleRequest.call(self, false, req, res);
	});

	self.httpServer.on('upgrade', function () {
		self.handleUpgrade.apply(self, arguments);
	});
	
	try {
		proxy = httpProxy.createProxyServer({});
	} catch (e) {
		console.log(colors.red('ERROR: ') + 'Proxy threw error: ' + e);
	}

	proxy.on('proxyError', function (err, req, res) {
		var route;

		if (self.configData && self.configData.routerTable) {
			if (self.configData.routerTable[req.headers.host] !== null) {
				route = self.configData.routerTable[req.headers.host];

				if (route.errorRedirect) {
					res.writeHead(302, {'Location': route.errorRedirect});
					res.end();
				} else {
					self.doErrorResponse(404, res);
github kunwu / WeixinCrawler / js / proxy.js View on Github external
try {
    var dbgMsgList = 0;
    var http = require('http'),
        httpProxy = require('http-proxy');

    var proxy = httpProxy.createProxyServer({});
    var requestInfoForHistoryList = null;

    var server = require('http').createServer(function (req, res) {

        var ts = new Date().toISOString().replace(/[-:Z]/g, '').replace('T', '_');

        console.log(ts + '|' + req.url);

        if (dbgMsgList == 1) {
            proxy.web(req, res, { target: req.url });
        } else if (req.url.indexOf('http://monitor.uu.qq.com/analytics/upload') == 0) {
            console.log('skip tencent analytics.');
            res.writeHead(200);
            res.end();
        } else if (req.url.indexOf('http://mp.weixin.qq.com/mp/getmasssendmsg?') == 0) {
            var aryHeaders = [];
github Nealyang / React-Express-Blog-Demo / server / server.js View on Github external
const app = new Express();
const port = config.port;

app.use('/api',(req,res)=>{
    proxy.web(req,res,{target:targetUrl})
});


app.use('/', connectHistoryApiFallback());
app.use('/',Express.static(path.join(__dirname,"..",'build')));
app.use('/',Express.static(path.join(__dirname,"..",'static')));


const targetUrl = `http://${config.apiHost}:${config.apiPort}`;
const proxy = httpProxy.createProxyServer({
    target:targetUrl
});

app.use(compression());
app.use(favicon(path.join(__dirname,'..','static','favicon.ico')));



//热更新
if(process.env.NODE_ENV!=='production'){
    const Webpack = require('webpack');
    const WebpackDevMiddleware = require('webpack-dev-middleware');
    const WebpackHotMiddleware = require('webpack-hot-middleware');
    const webpackConfig = require('../webpack.dev');

    const compiler = Webpack(webpackConfig);
github glacejs / glace-js / lib / proxy / httpProxy.js View on Github external
var HttpProxy = module.exports = function (opts) {

    BaseProxy.call(this, opts);

    this.proxyUrl = null;
    this._url = opts.url;
    this._server = null;

    var parsedUrl = url.parse(this._url);

    expect(["http:", "https:"],
           "Unsupported protocol").include(parsedUrl.protocol);

    if (parsedUrl.protocol === "https:") {

        this._proxy = httpProxy.createProxyServer({
            target: "https://" + parsedUrl.host,
            agent: https.globalAgent,
            headers: { host: parsedUrl.hostname },
            proxyTimeout: this._timeout,
        });

    } else {

        this._proxy = httpProxy.createProxyServer({
            target: {
                host: parsedUrl.hostname,
                port: parsedUrl.port,
            },
            proxyTimeout: this._timeout,
        });
    };
github zeroc-ice / ice-demos / typescript / browser / bin / HttpServer.js View on Github external
function(conf)
                {
                    proxies[conf.resource] = {
                        server: httpProxy.createProxyServer({target : conf.target, secure : false}),
                        protocol: conf.protocol };
                });
        }