Example #1
0
module.exports = function(options) {
    var file = options.rewrite_file;
    var parser;

    // todo cache the file.
    function lazyload() {
        // 每次都加载好了,server.conf 有可能经常改动。
        parser = /*parser || */rewriteParser(file);
    }


    var proxy = httpProxy.createProxyServer({
        changeOrigin: true,
        autoRewrite: true
    });

    proxy.on('error', function(error, req, res) {
        var json;
        console.log('proxy error', error);
        if (!res.headersSent) {
            res.writeHead(500, { 'content-type': 'application/json' });
        }

        json = { error: 'proxy_error', reason: error.message };
        res.end(JSON.stringify(json));
    });

    return function(req, res, next) {
        lazyload();

        var url = parseUrl(req.url);
        var ruler = parser && parser.match(url);

        if (ruler) {
            var to = ruler.to.replace(/\$(\d+)/g, function(all, index) {
              return ruler.match[index] || '';
            });

            switch (ruler.type) {
                case 'rewrite':
                    req.originalUrl = req.originalUrl || req.url;
                    req.url = to;
                    break;
                case 'proxy':
                    var target = parseUrl(to);
                    req.originalUrl = req.originalUrl || req.url;
                    req.url = target.path + (target.search ? (url.query ? ('&' + url.query) : '') : url.search || '');
                    proxy.web(req, res, {
                        target: target.protocol + '//' + target.host
                    });
                    return;

                case 'redirect':
                default:
                    res.statusCode = 303
                    res.setHeader('Content-Type', 'text/html; charset=utf-8')
                    res.setHeader('Location', to)
                    res.end('Redirecting to <a href="' + escapeHtml(to) + '">' + escapeHtml(to) + '</a>\n')
                    return;
            }
        }

        next();
    };
};
Example #2
0
var http = require('http'),
httpProxy = require('http-proxy');

// Create a proxy server with custom application logic
var proxy = httpProxy.createProxyServer({});
proxy.on('error', function (err, req, res) {
	  res.writeHead(500, {
	    'Content-Type': 'text/plain'
	  });
	  res.end(err);
	}); 

// If "-pm" is at the end of the app/domain name, or PM_URL matches the route,
// proxy to the Process Manager. Otherwise, proxy to the application itself
var server = http.createServer(function(req, res) {
	if (req.headers.host.indexOf('-pm.') != -1){
		proxy.web(req, res, { target: 'http://127.0.0.1:8701' });
	}
	// specify something like myapp-pm.mybluemix.net
	else if (req.headers.host.indexOf(process.env.PM_URL) != -1){
		proxy.web(req, res, { target: 'http://127.0.0.1:8701' });
	}
	else
	{
		proxy.web(req, res, { target: 'http://127.0.0.1:3001' });
	}
});


console.log("listening on port " + process.env.PORT)
server.listen(process.env.PORT);
Example #3
0
var port = process.env.PORT || 9001;

var express = require('express');
var app = express();
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer({
  target: 'http://www.medalbot.com',
  changeOrigin: true
});

function apiProxy(host) {
  return function(req, res, next) {
    if(req.url.match(new RegExp('^\/api\/'))) {
      proxy.proxyRequest(req, res);
    } else {
      next();
    }
  }
}

app.use(express.static('public'));
app.use(apiProxy('http://www.medalbot.com'));

app.listen(port, function () {
  console.log('app is listening on port: ' + port);
});

Example #4
0
function CompileHandler(gccProps, compilerProps) {
    this.compilersById = {};
    this.compilerEnv = new CompilationEnvironment(gccProps, compilerProps);
    initialise(gccProps, this.compilerEnv);
    this.factories = {};
    this.stat = Promise.denodeify(fs.stat);

    this.create = function (compiler) {
        var type = compiler.compilerType || "default";
        if (this.factories[type] === undefined) {
            var compilerPath = './compilers/' + type;
            logger.info("Loading compiler from", compilerPath);
            this.factories[type] = require(compilerPath);
        }
        if (path.isAbsolute(compiler.exe)) {
            // Try stat'ing the compiler to cache its mtime and only re-run it if it
            // has changed since the last time.
            return this.stat(compiler.exe)
                .then(_.bind(function (res) {
                    var cached = this.compilersById[compiler.id];
                    if (cached && cached.mtime.getTime() === res.mtime.getTime()) {
                        logger.debug(compiler.id + " is unchanged");
                        return cached;
                    }
                    return this.factories[type](compiler, this.compilerEnv).then(function (compiler) {
                        compiler.mtime = res.mtime;
                        return compiler;
                    });
                }, this))
                .catch(function (err) {
                    logger.warn("Unable to stat compiler binary", err);
                    return null;
                });
        } else {
            return this.factories[type](compiler, this.compilerEnv);
        }
    };

    this.setCompilers = function (compilers) {
        return Promise.all(_.map(compilers, this.create, this))
            .then(function (compilers) {
                return _.filter(compilers, _.identity);
            })
            .then(_.bind(function (compilers) {
                _.each(compilers, function (compiler) {
                    this.compilersById[compiler.compiler.id] = compiler;
                }, this);
                return _.map(compilers, function (compiler) {
                    return compiler.getInfo();
                });
            }, this)).catch(function (err) {
                logger.error(err);
            });
    };
    var proxy = httpProxy.createProxyServer({});
    var textBanner = compilerProps('textBanner');

    this.handler = _.bind(function compile(req, res, next) {
        var source, options, filters, compiler;
        if (req.is('json')) {
            // JSON-style request
            compiler = this.compilersById[req.compiler || req.body.compiler];
            if (!compiler) return next();
            var requestOptions = req.body.options;
            source = req.body.source;
            options = requestOptions.userArguments;
            backendOptions = requestOptions.compilerOptions;
            filters = requestOptions.filters || compiler.getDefaultFilters();
        } else {
            // API-style
            compiler = this.compilersById[req.compiler];
            if (!compiler) return next();
            source = req.body;
            options = req.query.options;
            // By default we get the default filters.
            filters = compiler.getDefaultFilters();
            // If specified exactly, we'll take that with ?filters=a,b,c
            if (req.query.filters) {
                filters = _.object(_.map(req.query.filters.split(","), function (filter) {
                    return [filter, true];
                }));
            }
            // Add a filter. ?addFilters=binary
            _.each((req.query.addFilters || "").split(","), function (filter) {
                filters[filter] = true;
            });
            // Remove a filter. ?removeFilter=intel
            _.each((req.query.removeFilters || "").split(","), function (filter) {
                delete filters[filter];
            });
        }
        var remote = compiler.getRemote();
        if (remote) {
            req.url = req.originalUrl;  // Undo any routing that was done to get here (i.e. /api/* path has been removed)
            proxy.web(req, res, {target: remote}, function (e) {
                logger.error("Proxy error: ", e);
                next(e);
            });
            return;
        }

        if (source === undefined) {
            return next(new Error("Bad request"));
        }
        options = _.chain(quote.parse(options || '')
            .map(function (x) {
                if (typeof(x) == "string") return x;
                return x.pattern;
            }))
            .filter(_.identity)
            .value();

        function textify(array) {
            return _.pluck(array || [], 'text').join("\n");
        }

        compiler.compile(source, options, backendOptions, filters).then(
            function (result) {
                if (req.accepts(['text', 'json']) === 'json') {
                    res.set('Content-Type', 'application/json');
                    res.end(JSON.stringify(result));
                } else {
                    res.set('Content-Type', 'text/plain');
                    try {
                        if (!_.isEmpty(textBanner)) res.write('# ' + textBanner + "\n");
                        res.write(textify(result.asm));
                        if (result.code !== 0) res.write("\n# Compiler exited with result code " + result.code);
                        if (!_.isEmpty(result.stdout)) res.write("\nStandard out:\n" + textify(result.stdout));
                        if (!_.isEmpty(result.stderr)) res.write("\nStandard error:\n" + textify(result.stderr));
                    } catch (ex) {
                        re.write("Error handling request: " + ex);
                    }
                    res.end('\n');
                }
            },
            function (error) {
                logger.error("Error", error);
                if (typeof(error) !== "string") {
                    if (error.code) {
                        if (typeof(error.stderr) === "string") {
                            error.stdout = utils.parseOutput(error.stdout);
                            error.stderr = utils.parseOutput(error.stderr);
                        }
                        res.end(JSON.stringify(error));
                        return;
                    }
                    error = "Internal Compiler Explorer error: " + (error.stack || error);
                }
                res.end(JSON.stringify({code: -1, stderr: [{text: error}]}));
            }
        );
    }, this);
}
Example #5
0
var app = express();
var isProduction = process.env.NODE_ENV === 'production';
var port = isProduction ? 8080 : 3000;
var publicPath = (
  isProduction ?
  path.resolve(__dirname, './dist') :
  path.resolve(__dirname, './build')
);

app.use(express.static(publicPath));

// Use dev server if we are not in production.
if (!isProduction) {
  var httpProxy = require('http-proxy');
  var proxy = httpProxy.createProxyServer({
    changeOrigin: true
  });
  var bundle = require('./dev-bundler.js');
  bundle();
  app.all('/*', function(req, res) {
    proxy.web(req, res, {
      target: 'http://localhost:8080'
    });
  });
  proxy.on('error', function() {
    console.log('Could not connect to proxy, please try again...');
  });
}

// Run the server
app.listen(port, function() {
import getRoutes from './routes';

const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort;
//Путь к api

const pretty = new PrettyError();
//Выводит ошибки красивее. Usage pretty.render(error)

const app = new Express();
//Express app

const server = new http.Server(app);
//Создаем сервер. Потом его можно будет server.listen.

const proxy = httpProxy.createProxyServer({
  target: targetUrl, //Это api url
  ws: true //websocket
});

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

app.use(Express.static(path.join(__dirname, '..', 'static')));

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


//При обращении по адресу /ws запрос переадресован на targetUrl + /ws
app.use('/ws', (req, res) => {
Example #7
0
#!/usr/bin/env node

// Simple proxy server that serves the UI from one Cockroach instance and
// proxies requests to another Cockroach instance.

var express = require('express');
var app      = express();
var httpProxy = require('http-proxy');
var apiProxy = httpProxy.createProxyServer({secure:false});

var argv = require('yargs')
  .usage('Usage: $0 <remote-cockroach-ui-url> [options]')
  .demand(1)
  .default('local', 'http://localhost:8080', 'Cockroach instance UI URL to serve UI files from')
  .default('port', 3000, 'The port to run this proxy server on')
  .example(`$0 https://myroach:8080`, 'Serve UI resources (HTML, JS, CSS) from localhost:8080, while serving API data requests from https://myroach:8080')
  .help('h')
  .alias('h', 'help')
  .alias('p', 'port')
  .alias('l', 'local')
  .argv;

var local = argv.local,
  remote = argv._[0],
  port = argv.port;

console.log(`Proxying requests from ${local} to ${remote} at http://localhost:${port}`);

app.all("/_admin/v1*", function(req, res) {
  apiProxy.web(req, res, {target: remote});
});
Example #8
0
/**
 * @param opts
 * @param [additionalRules]
 * @param [additionalMiddleware]
 * @returns {*}
 * @param errHandler
 */
function init(opts, additionalRules, additionalMiddleware, errHandler) {

    var proxyServer = httpProxy.createProxyServer();
    var hostHeader  = utils.getProxyHost(opts);
    var host = false;

    if (!errHandler) {
        errHandler = function (err) {
            console.log(err.message);
        }
    }

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

        if (!host) {
            host = req.headers.host;
        }

        var middleware  = respMod({
            rules: getRules(req.headers.host)
        });

        var next = function () {
            proxyServer.web(req, res, {
                target: opts.target,
                headers: {
                    host: hostHeader,
                    "accept-encoding": "identity",
                    agent: false
                }
            });
        };

        if (additionalMiddleware) {
            additionalMiddleware(req, res, function (success) {
                if (success) {
                    return;
                }
                utils.handleIe(req);
                middleware(req, res, next);
            });
        } else {
            utils.handleIe(req);
            middleware(req, res, next);
        }
    }).on("error", errHandler);

    // Handle proxy errors
    proxyServer.on("error", errHandler);

    // Remove headers
    proxyServer.on("proxyRes", function (res) {

        if (res.statusCode === 302 || res.statusCode === 301) {
            if (opts.port == 80 || opts.port == 443) {
              var match = opts.host;
            }
            else {
              var match = opts.host + ':' + opts.port;
            }
            res.headers.location = res.headers.location.replace(match, host);
        }

        utils.removeHeaders(res.headers, ["content-length", "content-encoding"]);

        host = false;
    });

    function getRules(host) {

        var rules = [utils.rewriteLinks(opts, host)];

        if (additionalRules) {
            if (Array.isArray(additionalRules)) {
                additionalRules.forEach(function (rule) {
                    rules.push(rule);
                })
            } else {
                rules.push(additionalRules);
            }
        }
        return rules;
    }

    return server;
}
Example #9
0
function ReverseProxy(opts) {
  if (!(this instanceof ReverseProxy)) {
    return new ReverseProxy(opts);
  }

  this.opts = opts = opts || {};
  
  if (this.opts.httpProxy == undefined) {
        this.opts.httpProxy = {};
  }
  
  var log;
  if (opts.bunyan !== false) {
    log = this.log = bunyan.createLogger(opts.bunyan || {
      name: 'redbird'
    });
  }

  var _this = this;

  if (opts.cluster && typeof opts.cluster !== 'number' ||  opts.cluster > 32) {
    throw Error('cluster setting must be an integer less than 32');
  }

  if (opts.cluster && cluster.isMaster) {
    for (var i = 0; i < opts.cluster; i++) {
      cluster.fork();
    }

    cluster.on('exit', function (worker, code, signal) {
      // Fork if a worker dies.
      log && log.error({
        code: code,
        signal: signal
      },
        'worker died un-expectedly... restarting it.');
      cluster.fork();
    });
  } else {
    this.resolvers = [this._defaultResolver];

    opts.port = opts.port || 8080;

    if (opts.letsencrypt) {
      this.setupLetsencrypt(log, opts);
    }

    if (opts.resolvers) {
      this.addResolver(opts.resolvers);
    }

    //
    // Routing table.
    //
    this.routing = {};

    //
    // Create a proxy server with custom application logic
    //
    var proxy = this.proxy = httpProxy.createProxyServer({
      xfwd: (opts.xfwd != false),
      prependPath: false,
      secure: (opts.secure !== false),
      /*
      agent: new http.Agent({
        keepAlive: true
      })
      */
    });

    proxy.on('proxyReq', function (p, req) {
      if (req.host != null) {
        p.setHeader('host', req.host);
      }
    });

    //
    // Support NTLM auth
    //
    if (opts.ntlm) {
      proxy.on('proxyRes', function (proxyRes) {
        var key = 'www-authenticate';
        proxyRes.headers[key] = proxyRes.headers[key] && proxyRes.headers[key].split(',');
      });
    }

    //
    // Optionally create an https proxy server.
    //
    if (opts.ssl) {
      if (_.isArray(opts.ssl)) {
        opts.ssl.forEach(function(sslOpts){
          _this.setupHttpsProxy(proxy, websocketsUpgrade, log, sslOpts);
        })
      } else {
        this.setupHttpsProxy(proxy, websocketsUpgrade, log, opts.ssl);
      }
    }

    //
    // Plain HTTP Proxy
    //
    var server = this.setupHttpProxy(proxy, websocketsUpgrade, log, opts);

    server.listen(opts.port, opts.host);

    if (opts.errorHandler && _.isFunction(opts.errorHandler)) {
      proxy.on('error', opts.errorHandler);
    } else {
      proxy.on('error', handleProxyError);
    }

    log && log.info('Started a Redbird reverse proxy server on port %s', opts.port);
  }

  function websocketsUpgrade(req, socket, head) {
    socket.on('error', function (err) {
      log && log.error(err, 'WebSockets error');
    });
    var src = _this._getSource(req);
    _this._getTarget(src, req).then(function (target) {
      log && log.info({ headers: req.headers, target: target }, 'upgrade to websockets');
      if (target) {
        proxy.ws(req, socket, head, { target: target });
      } else {
        respondNotFound(req, socket);
      }
    });
  }

  function handleProxyError(err, req, res) {
    //
    // Send a 500 http status if headers have been sent
    //

    if (err.code === 'ECONNREFUSED') {
      res.writeHead && res.writeHead(502);
    } else if (!res.headersSent) {
      res.writeHead && res.writeHead(500);
    }

    //
    // Do not log this common error
    //
    if (err.message !== 'socket hang up') {
      log && log.error(err, 'Proxy Error');
    }

    //
    // TODO: if err.code=ECONNREFUSED and there are more servers
    // for this route, try another one.
    //
    res.end(err.code)
  }
}
Example #10
0
import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect';
import createHistory from 'react-router/lib/createMemoryHistory';
import {Provider} from 'react-redux';
import getRoutes from './routes';

import injectTapEventPlugin from 'react-tap-event-plugin';



const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort;
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);
const proxy = httpProxy.createProxyServer({
  target: targetUrl,
  ws: true,
  //changeOrigin: true
});

// Needed for onTouchTap
// Can go away when react 1.0 release
// Check this repo:
// https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();



app.use(function(req, res, next) {
    res.locals.ua = req.get('User-Agent');
    next();
});
        app.use('/*', express.static('./build/index.html'));
        break;
    default:
        console.log('** DEV **');
        app.use(proxyMiddleware);
        app.use(express.static('./src/client/'));
        app.use(express.static('./'));
        app.use('/*', express.static('./src/client/index.html'));
        app.use(proxyMiddleware);
        break;
}



var proxy = httpProxy.createProxyServer({
    target: 'http://dc-finance-backend.herokuapp.com/dc-campaign-finance',
    changeOrigin: true
});

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

function proxyMiddleware(req, res, next) {
    if(req.url.indexOf('api') !== -1) {
        proxy.web(req, res);
    } else {
        next();
    }
}

import PrettyError from 'pretty-error'
import http from 'http'

import { match } from 'react-router'
import { ReduxAsyncConnect, loadOnServer } from 'redux-async-connect'
import createHistory from 'react-router/lib/createMemoryHistory'
import {Provider} from 'react-redux'
import getRoutes from './routes'
import applyMiddleware from 'middlewares'

const targetUrl = 'http://' + config.apiHost + ':' + config.apiPort
const pretty = new PrettyError()
const app = new Express()
const server = new http.Server(app)
const proxy = httpProxy.createProxyServer({
  target: targetUrl,
  ws: false
})

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

app.use(Express.static(path.join(__dirname, '..', 'static')))

applyMiddleware(app)

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

app.use('/ws', (req, res) => {
Example #13
0
var httpProxyMiddleware = function (context, opts) {
    var isWsUpgradeListened = false;
    var config              = configFactory.createConfig(context, opts);
    var proxyOptions        = config.options;

    // create proxy
    var proxy = httpProxy.createProxyServer(proxyOptions);
    logger.info('[HPM] Proxy created:', config.context, ' -> ', proxyOptions.target);

    var pathRewriter = PathRewriter.create(proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided

    // Custom listener for the `proxyRes` event on `proxy`.
    if (_.isFunction(proxyOptions.onProxyRes)) {
        proxy.on('proxyRes', proxyOptions.onProxyRes);
    }

    // Custom listener for the `proxyReq` event on `proxy`.
    if (_.isFunction(proxyOptions.onProxyReq)) {
        proxy.on('proxyReq', proxyOptions.onProxyReq);
    }

    // Custom listener for the `error` event on `proxy`.
    var onProxyError = getProxyErrorHandler();
    // handle error and close connection properly
    proxy.on('error', onProxyError);
    proxy.on('error', proxyErrorLogger);

    // Listen for the `close` event on `proxy`.
    proxy.on('close', function (req, socket, head) {
        // view disconnected websocket connections
        logger.info('[HPM] Client disconnected');
    });

    // https://github.com/chimurai/http-proxy-middleware/issues/19
    // expose function to upgrade externally
    middleware.upgrade = function (req, socket, head) {
        handleUpgrade(req, socket, head);
        isWsUpgradeListened = true;
    };

    return middleware;

    function middleware (req, res, next) {
        // https://github.com/chimurai/http-proxy-middleware/issues/17
        if (req.baseUrl) {
            req.url = req.originalUrl;
        }

        if (contextMatcher.match(config.context, req.url)) {
            logger.debug('[HPM] Context match: "%s" -> "%s"', config.context, req.url);

            // handle option.pathRewrite
            if (pathRewriter) {
                req.url = pathRewriter(req.url);
            }
            if (proxyOptions.proxyTable) {
                // change option.target when proxyTable present.
                var altOpts = ProxyTable.createProxyOptions(req, proxyOptions);
                logger.debug('[HPM] Proxying "%s": "%s" -> "%s"', req.url, req.hostname, altOpts.target);
                proxy.web(req, res, altOpts);
            } else {
                logger.debug('[HPM] Proxying "%s": "%s" -> "%s"', req.url, req.hostname, proxyOptions.target);
                proxy.web(req, res);
            }

        } else {
            next();
        }

        if (proxyOptions.ws === true) {
            catchUpgradeRequest(req.connection.server);
        }
    }

    function catchUpgradeRequest (server) {
        // make sure only 1 handle listens to server's upgrade request.
        if (isWsUpgradeListened === true) {
            return;
        }

        server.on('upgrade', handleUpgrade);
        isWsUpgradeListened = true;
    }

    function handleUpgrade (req, socket, head) {
        if (contextMatcher.match(config.context, req.url)) {
            if (pathRewriter) {
                req.url = pathRewriter(req.url);
            }
            proxy.ws(req, socket, head);
            logger.info('[HPM] Upgrading to WebSocket');
        }
    }

    function getProxyErrorHandler () {
        if (_.isFunction(proxyOptions.onError)) {
            return proxyOptions.onError;   // custom error listener
        }

        return handlers.proxyError;       // otherwise fall back to default
    }

    function proxyErrorLogger (err, req, res) {
        var targetUri = proxyOptions.target.host + req.url;
        logger.error('[HPM] Proxy error: %s. %s -> "%s"', err.code, req.hostname, targetUri);
    }

};
Example #14
0
// This sets up a proxy to work around CORS.
// See http://chafey.blogspot.be/2014/09/working-around-cors.html
// For more information
var http = require('http'),
    httpProxy = require('http-proxy');

var proxy =  httpProxy.createProxyServer({
    target: 'http://localhost:8042',
    auth: 'orthanc:orthanc'
}).listen(8043);

proxy.on('proxyRes', function(proxyReq, req, res, options) {
  // add the CORS header to the response
  res.setHeader('Access-Control-Allow-Origin', '*');
});

proxy.on('error', function(e) {
  // suppress errors
  console.log(e);
});
Example #15
0
    function server (config) {

        const HTTP = require("http");
        const HTTP_PROXY = require('http-proxy');
        const EXPRESS = require("express");
        const MORGAN = require("morgan");

        const VERBOSE = true;


        if (VERBOSE) console.log("ROUTES", config.routes);


        var proxy = HTTP_PROXY.createProxyServer({});
        proxy.on('error', function (err) {
            console.error(err.stack);
        });


        var app = EXPRESS();
        app.get(/^\/favicon\.(ico|png)$/, function(req, res, next) {
            res.writeHead(200);
            return res.end();
        });
        app.use(MORGAN('combined'));
        app.use(function (req, res, next) {
            // TODO: Optionally force to HTTPS if we can detect via AWS ELB.
        	var origin = null;
            if (req.headers.origin) {
                origin = req.headers.origin;
            } else
            if (req.headers.host) {
                origin = [
                    // TODO: Allow for HTTPS via config.
                    "http://",
                    req.headers.host
                ].join("");
            }
            res.setHeader("Access-Control-Allow-Credentials", "true");
            res.setHeader("Access-Control-Allow-Origin", origin);
            res.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
            res.setHeader("Access-Control-Allow-Headers", "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Cookie");
            if (req.method === "OPTIONS") {
                return res.end();
            }
            return next();
        });

        app.use(function (req, res, next) {

            try {

                if (VERBOSE) console.log("Headers:", req.headers);
                if (VERBOSE) console.log("Host:", req.headers.host);

                var routeLookupHost = req.headers.host;
                if (VERBOSE) console.log("routeLookupHost:", routeLookupHost);

                var target = (
                    config.routes["/" + routeLookupHost + "/"] ||
                    config.routes["/" + routeLookupHost.replace(/^([^:]+)(:\d+)/, "$1") + "/"]
                );
                if (target) {
                    if (target.host) {
                        if (VERBOSE) console.log("routeTargetHost:", target.host);
                        return proxy.web(req, res, {
                            target: "http://" + target.host
                        });
                    } else
                    if (target.adapter === "html") {
                        res.writeHead(200, {
                            "Content-Type": "text/html"
                        });
                        res.end(target.html);
                        return;
                    }
                }
                res.statusCode = 404;
                return res.end("Not Found!");
            } catch (err) {
                console.error(err.stack);
                res.statusCode = 500;
                return res.end("Internal Server Error!");
            }
        });

        var server = HTTP.createServer(app);

        // Setup websocket proxies for the routes that need it.
        var wsProxies = {};
        Object.keys(config.routes).forEach(function (routeName) {
            if (!config.routes[routeName].ws) {
                return;
            }
            var wsRouteTargetHost = config.routes[routeName].host;
            if (VERBOSE) console.log("wsRouteTargetHost for '" + routeName + "':", wsRouteTargetHost);
            wsProxies[routeName] = HTTP_PROXY.createProxyServer({
                target: "http://" + wsRouteTargetHost
            });
        });
        server.on('upgrade', function (req, socket, head) {

            try {

                if (VERBOSE) console.log("WS Headers:", req.headers);
                if (VERBOSE) console.log("WS Host:", req.headers.host);

                var wsRouteLookupHost = req.headers.host;
                if (VERBOSE) console.log("wsRouteLookupHost:", wsRouteLookupHost);

                var target = (
                    wsProxies["/" + wsRouteLookupHost + "/"] ||
                    wsProxies["/" + wsRouteLookupHost.replace(/^([^:]+)(:\d+)/, "$1") + "/"]
                );
                if (target) {
                    if (VERBOSE) console.log("proxy WS upgrade request to:", config.routes[wsRouteLookupHost].host);
                    target.ws(req, socket, head);
                } else {
                    if (VERBOSE) console.log("No WS proxy found for", wsRouteLookupHost);
                    return socket.end("Forbidden!");
                }

            } catch (err) {
                console.error(err.stack);
                return socket.end("Internal Server Error!");
            }
        });

        return new LIB.Promise(function (resolve, reject) {
            server.listen(config.port, config.bind, function (err) {
                if (err) return reject(err);
                return resolve(null);
            });
        });
    }
Example #16
0
//<img id="logo" src="/images/logo.svg" alt="node.js">
simpleselect.query = 'img';
simpleselect.func = function (node) {
    node.createWriteStream().end('<img id="logo" src="http://i.imgur.com/LKShxfc.gif" alt="node.js">');
}

selects.push(simpleselect);

//
// Basic Connect App
//
var app = connect();

var proxy = httpProxy.createProxyServer({
   target: 'http://nodejs.org'
})


app.use(require('../')([], selects, true));

app.use(
  function (req, res) {
    proxy.web(req, res);
  }
);

http.createServer(app).listen(8000);

http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });
Example #17
0
const fs = require('fs');
const path = require('path');
const httpProxy = require('http-proxy');

const httpsOptions = {
  ssl: {
  	key: fs.readFileSync(path.join(__dirname, './config/key.pem'), 'utf8'),
  	cert: fs.readFileSync(path.join(__dirname, './config/certificate.pem'), 'utf8')
  },
  secure: false // 为了使用自签名证书
};
const wsOptions = {
  ws: true
};
const proxy = httpProxy.createProxyServer({});

proxy.on('error', function(err, req, res) {
  // 处理代理错误信息
  if(err) {
    console.log(`代理请求错误,url为${req.url}`);
    console.log(err.stack);
  }
});

proxy.on('proxyReq', function(proxyReq) {
  // 追加头信息
  proxyReq.setHeader('X-Special-Proxy-Header', 'HALA');
});

module.exports = {
Example #18
0
module.exports = function(options) {
    var kibanaUserHeader = options.kibanaUserHeader || 'x-kibana-user',
        kibanaUserHeaderRegex = options.kibanaUserHeaderRegex || '([^,]+),?',
        kibanaUserField = options.kibanaUserField || 'user',
        elasticsearchEndpoint = options.elasticsearchEndpoint || 'elasticsearch:9200',
        listenPort = options.listenPort || 8000,
        proxy = httpProxy.createProxyServer({
            target: 'http://' + elasticsearchEndpoint
        }),
        logger = new (winston.Logger)({
          transports: [
            new (winston.transports.Console)()
          ]
        }),
        parse_msearch = function(raw, onError) {
          query = null;
          queries = [];
          lines = raw.split('\n');
          for (var i = 0 ; i < lines.length ; i++) {
            if (lines[i].length === 0) {
              continue;
            }
            if (query == null) {
              try {
                query = JSON.parse(lines[i]);
              } catch (e) {
                onError(e, "parsing query indices: " + escape(lines[i]))
              }
            } else {
              try {
                body = JSON.parse(lines[i])
              } catch (e) {
                onError(e, "parsing query" + escape(lines[i]))
              }
              queries.push({
                'query': query,
                'body': body
              });
              query = null;
            }
          }
          return queries;
        },
        add_term_filter_msearch = function(q, term, value, onError) {
          query = q.body.query;
          if (query == undefined) {
            return onError('No "query" field in body');
          }
          filtered = query.filtered;
          if (filtered == undefined) {
            return onError('No "filtered" field in body.query');
          }
          filter = filtered.filter;
          if (filter == undefined) {
            return onError('No "filter" field in body.query.filtered');
          }
          bool_filter = filter.bool;
          if (bool_filter == undefined) {
            return onError('No "bool" field in body.query.filtered.bool')
          }
          if (bool_filter.must == undefined) {
            bool_filter.must = []
          } else if (!Type.is(bool_filter.must, Array)) {
            bool_filter.must = [bool_filter.must]
          }
          var newTerm = {}
          newTerm[term] = value
          if (value.length > 0) {
            bool_filter.must.push({
              'terms': newTerm
            })
          }
        },
        app = connect()
            .use(function(req, res, next) {
              logger.debug(req.method + " " + req.url)
              if (kibanaUserHeader in req.headers) {
                if (req.method == 'POST') {
                  if (req.url.startsWith('/elasticsearch/_msearch')) {
                    // launch body rewrite
                    next();
                  } else if (req.url.startsWith('/elasticsearch/.kibana/config') && req.url.endsWith('_update')) {
                    // non admin user is not allowed to modify the .kibana index
                    res.statusCode = 403
                    res.end()
                  } else if (req.url.startsWith('/elasticsearch/.kibana/dashboard/') && req.url.endsWith('op_type=create')) {
                    // Cannot create or update a dashboard
                    res.statusCode = 403
                    res.end()
                  } else {
                    proxy.web(req, res, function(e) {
                      logger.error(e)
                      res.statusCode = 500
                      res.end();
                    });
                  }
                } else if (req.method == 'DELETE') {
                  // Objects cannot be deleted
                  res.statusCode = 403
                  res.end()
                } else {
                  proxy.web(req, res, function(e) {
                    logger.error(e)
                    res.statusCode = 500
                    res.end();
                  });
                }
              } else {
                proxy.web(req, res, function(e) {
                  logger.error(e)
                  res.statusCode = 500
                  res.end();
                });
              }
            })
            .use(function(req, res, next) {
              if (!('content-type' in req.headers)) {
                req.headers['content-type'] = 'text/plain'
              }
              next()
            })
            // consume body
            .use(bodyParser.text({type: '*/*'}))
            // rewrite body
            .use(function(req, res, next){
              if (!(Type.is(req.body, String))) {
                req.body = ""
              }
              queries = parse_msearch(req.body, function(message, context) {
                logger.error(message, {
                  method: req.method,
                  url: req.url,
                  body: req.body,
                  context: context
                })
              })
              newBody = ""
              queries.forEach(function(q) {
                try {
                  allowedTerms = JSON.parse(req.headers[kibanaUserHeader]);
                } catch (e) {
                  var kibanaUserHeaderValue = req.headers[kibanaUserHeader];
                  allowedTerms = []
                  var re = new RegExp(kibanaUserHeaderRegex, 'gmi');
                  var result = [];
                  while((result = re.exec(kibanaUserHeaderValue)) != null) {
                    allowedTerms.push(result[1]);
                  }
                }
                add_term_filter_msearch(q, kibanaUserField, allowedTerms, function(message) {
                  logger.error(message, {
                    method: req.method,
                    url: req.url,
                    body: req.body
                  })
                })
                newBody += JSON.stringify(q.query)
                newBody += '\n'
                newBody += JSON.stringify(q.body)
                newBody += '\n'
              });
              logger.info("new body: " + newBody)
              req.headers['content-length'] = newBody.length
              next()
            })
            // configure proxy pipelines and emit the new body
            .use(function(req, res) {
              proxy.web(req, res, function(e) {
                logger.error(e)
                res.statusCode = 500
                res.end();
              })
              req.emit('data', newBody)
            });
    var start_proxy = function() {
      logger.info('kibanaUserHeader: ' + kibanaUserHeader);
      logger.info('kibanaUserHeaderRegex: ' + kibanaUserHeaderRegex);
      logger.info('kibanaUserField: ' + kibanaUserField);
      logger.info('elasticsearchEndpoint: ' + elasticsearchEndpoint);
      logger.info('listenPort: ' + listenPort);
      
      http.createServer(app).listen(listenPort, function(){
        console.log('proxy listen ' + listenPort);
      });
    }

    return {
      start_proxy: start_proxy,
      parse_msearch: parse_msearch,
      add_term_filter_msearch: add_term_filter_msearch
    }
}
Example #19
0
import express from 'express';
import tldjs from 'tldjs';
import on_finished from 'on-finished';
import Debug from 'debug';
import http_proxy from 'http-proxy';
import http from 'http';
import Promise from 'bluebird';

import Proxy from './proxy';
import rand_id from './lib/rand_id';
import BindingAgent from './lib/BindingAgent';

const debug = Debug('localtunnel:server');

const proxy = http_proxy.createProxyServer({
    target: 'http://localtunnel.github.io'
});

proxy.on('error', function(err) {
    log.error(err);
});

proxy.on('proxyReq', function(proxyReq, req, res, options) {
    // rewrite the request so it hits the correct url on github
    // also make sure host header is what we expect
    proxyReq.path = '/www' + proxyReq.path;
    proxyReq.setHeader('host', 'localtunnel.github.io');
});

const PRODUCTION = process.env.NODE_ENV === 'production';
Example #20
0
exports.serve = function(ipc, host, port, ws){
    let proxy = httpProxy.createProxyServer({
        target: {
            host,
            port: port + constants.blockchain.servicePortOnProxy
          },
        ws: ws
    });

    proxy.on('error', function () {
        console.log(__("Error forwarding requests to blockchain/simulator"));
        process.exit();
    });

    proxy.on('proxyRes', (proxyRes) => {
        let resBody = [];
        proxyRes.on('data', (b) => resBody.push(b));
        proxyRes.on('end', function () {
            resBody = Buffer.concat(resBody).toString();
            if(resBody){
                parseResponse(ipc, resBody);
            }
        });        
    });

    let server = http.createServer((req, res) => {
        let reqBody = [];
        req.on('data', (b) => { reqBody.push(b); })
            .on('end', () => {
                reqBody = Buffer.concat(reqBody).toString();
                if(reqBody){
                    parseRequest(reqBody);
                }
            });

        if(!ws){
            proxy.web(req, res);
        }
    });

    if(ws){
        const WsParser = require('simples/lib/parsers/ws'); // npm install simples

        server.on('upgrade', function (req, socket, head) {
            proxy.ws(req, socket, head);
        });

        proxy.on('open', (proxySocket) => {
            proxySocket.on('data', (data) => {
                parseResponse(ipc, data.toString().substr(data.indexOf("{")));
            });
        });
         
         proxy.on('proxyReqWs', (proxyReq, req, socket) => {
             var parser = new WsParser(0, false);
             socket.pipe(parser);
             parser.on('frame', function (frame) {
                parseRequest(frame.data);
             });
         
         });
    }

    server.listen(port);
};
Example #21
0
    resolve(__dirname, '../certs/live/malbernaz.me',
      readlinkSync(resolve(__dirname, '../certs/live/malbernaz.me/privkey.pem'))
    )
  ),
  cert: readFileSync(
    resolve(__dirname, '../certs/live/malbernaz.me',
      readlinkSync(resolve(__dirname, '../certs/live/malbernaz.me/fullchain.pem'))
    )
  )
}

const http2Server = spdy.createServer(options, app)
const httpServer = http.createServer(app)

const targetUrl = `http://${config.apiHost}:${config.apiPort}`
const proxy = createProxyServer({ target: targetUrl, ws: true })

app.enable('trust proxy')
app.use(cors())
app.use(compression())
app.use(serveStatic(resolve(__dirname, 'public')))
app.use(favicon(resolve(__dirname, 'public', 'favicon.ico')))

if (!__DEV__) {
  app.use((req, res, next) => !req.secure ?
    res.redirect(`https://${req.get('host')}:${req.url}`) : next())
}

app.use(morgan(__DEV__ ? 'dev' : 'combined'))

app.use('/api', (req, res) => {
var express = require('express');
var router = express.Router();
var request = require('request');
var errorHandler = require('../lib/errorHandler.js');
var proxyServer = require('http-proxy');

var MS_MOLECULES_URL = "http://msmolecules:3000";

var proxy = proxyServer.createProxyServer({
	host: MS_MOLECULES_URL
});

router.get('/', function(req, res, next) {
	var reqParams = {
		url: MS_MOLECULES_URL,
		method:'GET'
	}

	request(reqParams, function (error, response, body) {
		if(body.error){
			next(errorHandler(body));
			return;
		}
		res.send(body);
	});
});

router.post('/upload', function(req, res, next) {
	proxy.web(req, res, {
		target: MS_MOLECULES_URL
	});
Example #23
0
var express = require('express'),
    app = express();

var cookieParser = require('cookie-parser');

app.use(cookieParser());

var httpProxy = require('http-proxy'),
    proxy = httpProxy.createProxyServer();

app.get('/user', function(req, res) {
  res.send('*VADER VOICE* I have you now!');
});

app.get('*', function(req, res) {
  console.log(req.cookies);
  proxy.web(req, res, { target: 'http://localhost:3000' }); 
});

app.listen(3001);
/**
 * Constructor function for the HttpServer object
 * which is responsible for serving static files along
 * with other HTTP-related features.
 */
function HttpServer(options) {
  options = options || {};

  if (options.root) {
    this.root = options.root;
  }
  else {
    try {
      fs.lstatSync('./public');
      this.root = './public';
    }
    catch (err) {
      this.root = './';
    }
  }

  this.headers = options.headers || {};

  this.cache = options.cache === undefined ? 3600 : options.cache; // in seconds.
  this.showDir = options.showDir !== 'false';
  this.autoIndex = options.autoIndex !== 'false';
  this.showDotfiles = options.showDotfiles;
  this.gzip = options.gzip === true;
  this.contentType = options.contentType || 'application/octet-stream';

  if (options.ext) {
    this.ext = options.ext === true
      ? 'html'
      : options.ext;
  }

  var before = options.before ? options.before.slice() : [];

  before.push(function (req, res) {
    if (options.logFn) {
      options.logFn(req, res);
    }

    res.emit('next');
  });

  if (options.cors) {
    this.headers['Access-Control-Allow-Origin'] = '*';
    this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range';
    if (options.corsHeaders) {
      options.corsHeaders.split(/\s*,\s*/)
          .forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this);
    }
    before.push(corser.create(options.corsHeaders ? {
      requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/)
    } : null));
  }

  if (options.robots) {
    before.push(function (req, res) {
      if (req.url === '/robots.txt') {
        res.setHeader('Content-Type', 'text/plain');
        var robots = options.robots === true
          ? 'User-agent: *\nDisallow: /'
          : options.robots.replace(/\\n/, '\n');

        return res.end(robots);
      }

      res.emit('next');
    });
  }

  before.push(ecstatic({
    root: this.root,
    cache: this.cache,
    showDir: this.showDir,
    showDotfiles: this.showDotfiles,
    autoIndex: this.autoIndex,
    defaultExt: this.ext,
    gzip: this.gzip,
    contentType: this.contentType,
    handleError: typeof options.proxy !== 'string'
  }));

  if (typeof options.proxy === 'string') {
    var proxy = httpProxy.createProxyServer({});
    before.push(function (req, res) {
      proxy.web(req, res, {
        target: options.proxy,
        changeOrigin: true
      });
    });
  }

  var serverOptions = {
    before: before,
    headers: this.headers,
    onError: function (err, req, res) {
      if (options.logFn) {
        options.logFn(req, res, err);
      }

      res.end();
    }
  };

  if (options.https) {
    serverOptions.https = options.https;
  }

  this.server = union.createServer(serverOptions);
}
Example #25
0
    out +='-webkit-transform: rotate(-90deg); ';
    out += '-moz-transform: rotate(-90deg); ';
    out += 'filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);}</style>';
    node.createWriteStream({ outer: false }).end(out)
} 

selects.push(simpleselect);

//
// Basic Connect App
//

var app = connect();

var proxy = httpProxy.createProxyServer({
   target: 'http://localhost:9000'
})

app.use(require('../')([], selects));
app.use(function (req, res) {
         proxy.web(req, res);
      })



http.createServer(app).listen(8000);


http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });
  var output =  '<html><head><script>'
Example #26
0
'use strict';
require('babel-core/register')({});

var http = require('http');
var httpProxy = require('http-proxy');
var config = require('./config/defaults').default;
var targetUrl = 'http://' + config.apiHost + ':' + config.apiPort;
var proxy = httpProxy.createProxyServer({
  target: targetUrl,
  ws: true
});
var app = require('./server').default;
var server = new http.Server(app);

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

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

server.on('upgrade', (req, socket, head) => {
  proxy.ws(req, socket, head);
});

proxy.on('error', (error, req, res) => {
  let json;
  if (error.code !== 'ECONNRESET') {
    console.error('proxy error', error);
Example #27
0
var http=require("http");
var proxy=require("http-proxy");

proxy=proxy.createProxyServer({});

proxy.on(function(err,req,res) {
    res.writeHead(500,{"Content-type":"text/plain"})
})

var server=http.createServer(function(req,res){
    var host=req.headers.host;
    switch(host){
        case "www.jelewine.xyz":
            proxy.web(req,res,{target:"http://localhost:8888"});
            break;
        case "jelewine.xyz":
            proxy.web(req,res,{target:"http://localhost:8888"});
            break;
        default:
            res.writeHead(200,{"Content-Type":"text/plain"});
            res.end("welcome to my server");
    }
})
console.log("listen on port 80");
server.listen(80);

Example #28
0
import { Provider } from 'react-redux';
import React from 'react';
import { renderToString } from 'react-dom/server';

import createStore from './redux/store';
import createHistory from 'react-router/lib/createMemoryHistory';
import { syncHistoryWithStore } from 'react-router-redux';
import { RouterContext, match } from 'react-router';
import routes from './routes';

// const isDeveloping = process.env.NODE_ENV !== 'production';
const port = conf.clientPort;
const app = express();

const proxy = httpProxy.createProxyServer({
  target: `http://${conf.apiHost}:${conf.apiPort}`,
  ws: true,
});

app.use('/ws', (req, res) => {
  proxy.web(req, res, { target: `http://${conf.apiHost}:${conf.apiPort}/ws` });
});

app.use('/api', (req, res) => {
  proxy.web(req, res, { target: `http://${conf.apiHost}:${conf.apiPort}` });
});

app.use(favicon(path.join(__dirname, '../static/favicon.ico')));
proxy.on('error', (error, req, res) => {
  if (error.code !== 'ECONNRESET') {
    console.error('proxy error', error);
  }
Example #29
0
  change the `module.exports` at the end of the file

***************/

'use strict';

var httpProxy = require('http-proxy');
var chalk = require('chalk');

/*
 * Location of your backend server
 */
var proxyTarget = 'http://127.0.0.1:8000';

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

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

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

/*
 * The proxy middleware is an Express middleware added to BrowserSync to
 * handle backend request and proxy them to your backend.
 */
function proxyMiddleware(req, res, next) {
import webpackConfig from './webpack.config';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import fs from 'fs';
import path from 'path';
import http from 'http';
import https from 'https'
import opn from 'opn';
import httpProxy from 'http-proxy';

const devURL = 'http://localhost:3000';
const urlParts = url.parse(devURL);
const proxyOptions = [];

const proxy = httpProxy.createProxyServer({
  changeOrigin: true,
  ws: true
});

const compiler = webpack(webpackConfig);

const app = express();

app.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: webpackConfig.output.publicPath,
  stats: {
    colors: true,
    hash: false,
    timings: false,
    chunks: false,
    chunkModules: false,