Exemplo n.º 1
0
gulp.task('watch-dev', ['build-styles-dev', 'validate-app-scripts'], function () {
    var proxy = proxyMiddleware('/geoserver', {target: 'http://demo.boundlessgeo.com'});
    var proxy2 = proxyMiddleware('/shapes/', {target: 'http://10.3.2.136:8000/'});
    var proxy3 = proxyMiddleware('/geoserver2', {target: 'http://172.17.0.3'});

    browserSync.init({
        port: 3000,
        server: {
            baseDir: ['./app','./.tmp'],
            middleware: [proxy, proxy2, proxy3]
        }
    });

    gulp.watch(paths.stylesAll, ['build-styles-dev']);
    gulp.watch(['./app/**/*.*', '!./app/**/*.+(css|less)']).on('change', browserSync.reload);
});
Exemplo n.º 2
0
gulp.task('browser-sync',['clean'], function() {
    browserSync.use(htmlInjector, {
        files: "*/*.html"
    });

    //设置代理
    var proxy = proxyMiddleware('/api', {
        target: 'http://localhost:8080',
        // headers: {
        //     host:'localhost'   // 这个挺关键
        // }
    });
    console.log(proxy);
    browserSync({
        server: {
            baseDir: "./",
            index: "/index.html",
            middleware: [proxy]
        },
        https: false
    });
    gulp.watch(['build/**/*']).on('change', function(file) {
        reload(file.path);
    });
    gulp.watch(['src/**/*']).on('change', function(file) {
        reload(file.path);
    });
    gulp.watch(['template/**/*']).on('change', function(file) {
        reload(file.path);
    });
});
module.exports = function createServer(config) {
    const server = express()
    const staticPath = path.resolve(process.cwd(), config.dir ? config.dir : config.outputAssetsPath)

    server.use(express.static(staticPath))
    server.use(morgan('dev'))

    if (config.apiProxy) {
        server.use(proxy(config.apiProxy.address, {
            target: config.apiProxy.host,
            ws: true,
            changeOrigin: true
        }))
    }

    server.listen(config.port, config.host, function () {
        logger.info(`\nserving file from ${staticPath}\nstatic-proxy-server is running...`)

        const serverUrl = url.format({
            protocol: config.https ? 'https' : 'http',
            hostname: config.host,
            port: config.port
        })

        logger.info(`opening ${serverUrl}`)
        open(serverUrl)
    })
}
Exemplo n.º 4
0
function browserSyncInit(baseDir, browser) {
  browser = browser === undefined ? 'default' : browser;

  var routes = null;
  if (baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
    routes = {
      '/bower_components': 'bower_components',
      '/.tmp': '.tmp'
    };
  }

  var server = {
    baseDir: baseDir,
    routes: routes,
    port: 3001
  };

  var ui = {
    port: 3002
  };

  var apiProxy = proxy('/api', {
    target: 'http://localhost:3003',
    changeOrigin: true
  });

  server.middleware = [apiProxy];

  browserSync.instance = browserSync.init({
    startPath: '/',
    server: server,
    browser: browser,
    ui: ui
  });
}
Exemplo n.º 5
0
Object.keys(proxyTable).forEach((context) => {
  let options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxyMiddleware(options.filter || context, options))
})
Exemplo n.º 6
0
gulp.task('serve', ['styles', 'elements'], function() {
  var proxy = proxyMiddleware('/v1/api', {target: 'tcp://localhost:3000'});
  browserSync({
    port: 5000,
    notify: false,
    logPrefix: 'Hivelife',
    snippetOptions: {
      rule: {
        match: '<span id="browser-sync-binding"></span>',
        fn: function(snippet) {
          return snippet;
        }
      }
    },
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: ['.tmp', 'app'],
      middleware: [proxy, historyApiFallback()]
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.css'], ['styles', reload]);
  gulp.watch(['app/elements/**/*.css'], ['elements', reload]);
  gulp.watch(['app/images/**/*'], reload);
});
Exemplo n.º 7
0
function browserSyncInit(baseDir, browser) {
  browser = browser === undefined ? 'default' : browser;

  var routes = null;
  if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
    routes = {
      '/bower_components': 'bower_components'
    };
  }

  var server = {
    baseDir: baseDir,
    routes: routes
  };

  /*
   * You can add a proxy to your backend by uncommenting the line below.
   * You just have to configure a context which will we redirected and the target url.
   * Example: $http.get('/users') requests will be automatically proxified.
   *
   * For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.9.0/README.md
   */
  server.middleware = proxyMiddleware('/api', {target: 'https://media.lottoland.com/', changeOrigin: true});

  browserSync.instance = browserSync.init({
    startPath: '/',
    server: server,
    browser: browser
  });
}
Exemplo n.º 8
0
Object.keys(proxyTable).forEach(function (context) {
  var options = proxyTable[context]
  if (typeof options === 'string') {
    options = { target: options }
  }
  app.use(proxyMiddleware(context, options))
})
Exemplo n.º 9
0
 middleware: function (connect, opt) {
     return [
         proxy('/api', {
             target: 'http://localhost:8000'
         })
     ];
 }
Exemplo n.º 10
0
gulp.task('serve', ['styles', 'scripts'], () => {
  const LocalProxy = proxy(['/bit_wrapper', '/main_html5', '/osmf_flash'], {
      target: 'http://localhost:' + (process.env.PORT || 8080),
      changeOrigin: true, // for vhosted sites, changes host header to match to target's host
      logLevel: 'debug'
  });
  browserSync({
    notify: false,
    port: 9000,
    server: {
      baseDir: ['.tmp', 'app'],
      routes: {
        '/node_modules': './node_modules',
        '/vendor': 'vendor'
      },
      middleware: [LocalProxy]
    }
  });

  gulp.watch([
    'app/*.html',
    'app/images/**/*'
  ]).on('change', reload);

  gulp.watch('app/styles/**/*.scss', ['styles']);
  gulp.watch('app/scripts/**/*.js', ['scripts']);
});
Exemplo n.º 11
0
function browserSyncInit(baseDir, browser) {
  browser = browser === undefined ? 'default' : browser;

  var routes = null;
  if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
    routes = {
      '/bower_components': 'bower_components'
    };
  }

  var server = {
    baseDir: baseDir,
    routes: routes
  };

  /*
   * You can add a proxy to your backend by uncommenting the line bellow.
   * You just have to configure a context which will we redirected and the target url.
   * Example: $http.get('/users') requests will be automatically proxified.
   *
   * For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.0.5/README.md
   */
  // server.middleware = proxyMiddleware('/users', {target: 'http://jsonplaceholder.typicode.com', proxyHost: 'jsonplaceholder.typicode.com'});
  server.middleware = proxyMiddleware(['/me', '/resource', '/login', '/logout'], {target: 'http://localhost:8080'});


  browserSync.instance = browserSync.init({
    startPath: '/',
    server: server,
    browser: browser
  });
}
Exemplo n.º 12
0
(function (c) {

    if (!c) {

        return;
    }

    const media = require('./front/media.json');

    if (c.prefix && c.schema && c.host && c.port) {

        // tlog('php_proxy mounting', JSON.stringify(Object.assign({}, c, {
        //     prefix: c.prefix.toString(),
        //     joinend: [c.schema,'://',c.host,':',c.port].join('')
        // }), null, 4));

        app.use(
            c.prefix,
            proxy(
                [c.schema,'://',c.host,':',c.port].join(''),
                {
                    changeOrigin: true,
                    pathRewrite: (path) => {

                        const match = path.match(c.prefix);

                        let url = match[2];

                        if (match[1] === '/media') {

                            url = '/media' + (url.split('?')[0]);

                            const parts = url.match(/^.*\[(.+)\]\.([a-z]{3})$/);

                            if ( ! parts ) {

                                throw `Filename should look like this: /media/images/fe/be/example-file[flag].jpg`;
                            }

                            if ( ! media[parts[1]] ) {

                                throw `Node: Flag '${parts[1]}' is not registered, allowed flags: ` + (Object.keys(media).join(', '));
                            }
                        }

                        tlog("proxy_pass:"******"configServer schema, prefix, host or port is wrong/missing " + JSON.stringify(c, null, 4);
    }

}(configServer.php_proxy && Object.assign(configServer.php_proxy, configPublic.php_proxy)));
Exemplo n.º 13
0
app.prepare().then(() => {
  server = express()

  if (dev || process.env.BACKEND_PROXY) {
    const proxyMiddleware = require('http-proxy-middleware')
    const backendUrl = process.env.BACKEND_URL || 'http://127.0.0.1:5000'
    server.use(proxyMiddleware('/api/', { target: backendUrl }))
    server.use(proxyMiddleware('/auth/', { target: backendUrl }))
  }

  server.get('*', (req, res) => handle(req, res))

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})
Exemplo n.º 14
0
Object.keys(proxyTable).forEach(function(context) {
    var options = proxyTable[context]
        // 格式化options,例如将'www.example.com'变成{ target: 'www.example.com' }
    if (typeof options === 'string') {
        options = { target: options }
    }
    app.use(proxyMiddleware(options.filter || context, options))
})
Exemplo n.º 15
0
function addMiddleware(devServer) {
  // `proxy` lets you to specify a fallback server during development.
  // Every unrecognized request will be forwarded to it.
  var proxy = require(paths.appPackageJson).proxy;
  devServer.use(historyApiFallback({
    // Paths with dots should still use the history fallback.
    // See https://github.com/facebookincubator/create-react-app/issues/387.
    disableDotRule: true,
    // For single page apps, we generally want to fallback to /index.html.
    // However we also want to respect `proxy` for API calls.
    // So if `proxy` is specified, we need to decide which fallback to use.
    // We use a heuristic: if request `accept`s text/html, we pick /index.html.
    // Modern browsers include text/html into `accept` header when navigating.
    // However API calls like `fetch()` won’t generally accept text/html.
    // If this heuristic doesn’t work well for you, don’t use `proxy`.
    htmlAcceptHeaders: proxy ?
      ['text/html'] :
      ['text/html', '*/*']
  }));
  if (proxy) {
    if (typeof proxy !== 'string') {
      console.log(chalk.red('When specified, "proxy" in package.json must be a string.'));
      console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'));
      console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'));
      process.exit(1);
    }

    // Otherwise, if proxy is specified, we will let it handle any request.
    // There are a few exceptions which we won't send to the proxy:
    // - /index.html (served as HTML5 history API fallback)
    // - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
    // - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
    // Tip: use https://jex.im/regulex/ to visualize the regex
    var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/;

    // Pass the scope regex both to Express and to the middleware for proxying
    // of both HTTP and WebSockets to work without false positives.
    var hpm = httpProxyMiddleware(pathname => mayProxy.test(pathname), {
      target: proxy,
      logLevel: 'silent',
      onError: onProxyError(proxy),
      secure: false,
      changeOrigin: true,
      ws: true
    });
    devServer.use(mayProxy, hpm);

    // Listen for the websocket 'upgrade' event and upgrade the connection.
    // If this is not done, httpProxyMiddleware will not try to upgrade until
    // an initial plain HTTP request is made.
    devServer.listeningApp.on('upgrade', hpm.upgrade);
  }

  // Finally, by now we have certainly resolved the URL.
  // It may be /index.html, so let the dev server try serving it again.
  devServer.use(devServer.middleware);
}
Exemplo n.º 16
0
        const getProxyMiddleware = (proxyConfig) => {
          const context = proxyConfig.context || proxyConfig.path;

          // It is possible to use the `bypass` method without a `target`.
          // However, the proxy middleware has no use in this case, and will fail to instantiate.
          if (proxyConfig.target) {
            return httpProxyMiddleware(context, proxyConfig);
          }
        };
Exemplo n.º 17
0
  conf.backendProxy.forEach(function(proxyRoute) {
    var options = proxyRoute.options;

    if (agent) {
      options.agent = agent;
    }

    server.middleware.push(proxyMiddleware(proxyRoute.context, options));
  });
Exemplo n.º 18
0
 middleware: function(conn, opt) {
     return [
         proxy('!/app/**', {
             target: options.serverUrl,
             changeOrigin: false,
             ws: true
         })
     ];
 }
Exemplo n.º 19
0
 middleware: function(connect, opt) {
   return [
     proxy('/smsApi', {
         // target: 'http://localhost:19000', //模拟接口
         target: 'http://192.168.8.236', //研发环境
         // target: 'http://192.168.8.237', //测试环境
         changeOrigin: true
     })
   ]
 }
Exemplo n.º 20
0
	developMiddleware: app => {
		app.use(
			"/.netlify/functions/",
			proxy({
				target: "http://localhost:9000",
				pathRewrite: {
					"/.netlify/functions/": ""
				}
			})
		)
	}
Exemplo n.º 21
0
export function startProxy({ port }) {
  const proxyApp = connect().use(proxy({
    target: `http://localhost:${port}`,
    ws: true,
    xfwd: true,
    changeOrigin: true,
    logLevel: 'silent',
  }));

  return { proxyApp };
}
Exemplo n.º 22
0
gulp.task('browserSync', function() {
	// 代理配置, 实现环境切换
	var middleware = proxyMiddleware(['/users'], {target: target, changeOrigin: true});
	browserSync({
		server: {
			baseDir: './',
			index: 'src/index.html',
			middleware: middleware
		}
	});
});
Exemplo n.º 23
0
module.exports = function createServer (compiler, options) {
  var server = express()

  var devMiddleWare = require('webpack-dev-middleware')(compiler, {
    quiet: true
  })

  server.use(devMiddleWare)
  server.use(require('webpack-hot-middleware')(compiler, {
    log: () => null
  }))
  server.use(require('connect-history-api-fallback')({index: '/'}))

  var mfs = devMiddleWare.fileSystem
  var file = path.join(compiler.options.output.path, 'index.html')

  // proxy api requests
  if (typeof options.proxy === 'string') {
    server.use(proxyMiddleware('/api', {
      target: options.proxy,
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''
      }
    }))
  } else if (typeof options.proxy === 'object') {
    Object.keys(options.proxy).forEach(function (context) {
      var proxyOptions = options.proxy[context]
      if (typeof proxyOptions === 'string') {
        proxyOptions = {
          target: proxyOptions,
          changeOrigin: true,
          pathRewrite: {
            [`^${context}`]: ''
          }
        }
      }
      server.use(proxyMiddleware(context, proxyOptions))
    })
  }

  server.get('/', (req, res) => {
    devMiddleWare.waitUntilValid(() => {
      const html = mfs.readFileSync(file)
      res.end(html)
    })
  })

  if (options.setup) {
    options.setup(server)
  }

  return server
}
Exemplo n.º 24
0
 middleware: function(connect, opt){
   return [
     ['/bower_components', connect["static"]('./bower_components')],
     ['/api', proxy({
       target: 'http://localhost:5760',
       pathRewrite: {
         '^/api' : ''
       },
       changeOrigin: true
     })]
   ]
 }
Exemplo n.º 25
0
gulp.task('serve', ['build', 'watch'], function () {

    browserSync.init({
        server: {
            baseDir: path.output.basedir,
            routes: {
                '/lib': path.lib
            },
            middleware: proxyMiddleware('/api', {target: 'https://media.lottoland.com/', changeOrigin: true})
        }
    });
});
Exemplo n.º 26
0
function drakovProxy(){
  var argv = {
      sourceFiles: 'app/{elements,bower_components}/**/*-mock.md',
      serverPort: 5001,
      public : true
  };
  drakov.run(argv);

  return proxy('/api', {
    target: 'http://localhost:5001/',
    logLevel: 'debug'});
}
Exemplo n.º 27
0
function routeApi(service, port) {
    
    return proxy("/api/v*/" + service + "/**", {
        target: "http://localhost:" + port,
        logLevel: "debug",
        pathRewrite: function (path, req) {
            return path
                .replace("/api", "")
                .replace("/" + service + "/", "/");
        }
    });
}
gulp.task("serve", ["watch"], function () {
    var proxy = proxyMiddleware('/api', {
        target: 'http://wanna-drink-api.localtest.me:5000'
    });
    // initialize browser sync
    browserSync.init({
        server: destPath,
        host: 'wanna-drink.localtest.me',
        open: 'external',
        middleware: [proxy]
    });
});
Exemplo n.º 29
0
gulp.task('serve', ['styles', 'fonts'], function () {
  var proxyAuth = proxyMiddleware('/auth/', {target: 'http://0.0.0.0:8000'});
  var proxyApi = proxyMiddleware('/api/', {target: 'http://0.0.0.0:8000'});
  var proxyHome = proxyMiddleware('/home/', {target: 'http://0.0.0.0:8000'});
  var proxyAdmin = proxyMiddleware('/admin/', {target: 'http://0.0.0.0:8000'});
  var proxyPay = proxyMiddleware('/pay/', {target: 'http://0.0.0.0:8000'});
  var proxyPassword = proxyMiddleware('/password/', {target: 'http://0.0.0.0:8000'});

  browserSync({
    notify: false,
    port: 9000,
    server: {
      baseDir: ['.tmp', 'app'],
      routes: {
        '/bower_components': 'bower_components',
        '/scripts': 'app/scripts'
      },
      middleware: [proxyAuth, proxyApi, proxyHome, proxyAdmin, proxyPay, proxyPassword],
    }
  });

  // watch for changes
  gulp.watch([
    // 'app/*.html',
    // 'app/scripts/**/*.js',
    'app/**/*.html',
    'app/**/*.js',
    'app/images/**/*',
    '.tmp/fonts/**/*'
  ]).on('change', reload);

  gulp.watch('app/**/*.scss', ['styles']);
  gulp.watch('app/fonts/**/*', ['fonts']);
  gulp.watch('bower.json', ['wiredep', 'fonts']);
});
Exemplo n.º 30
0
    /**
     * Creates http proxy
     * @private
     * @param {Object} httpProxy - proxy parameters
     * @returns
     */
    function createHttpProxy(app, httpProxy){
        var sep = path.sep; //The platform-specific file separator. '\\' or '/'
        try {
            var localPath = httpProxy.localPath || sep,
                remotePath = httpProxy.remotePath || sep,
                serverAddr = httpProxy.server;

            //localPath & remotePath should always starts with /
            if (!localPath.startsWith(sep)) {
                localPath = sep + localPath;
            }
            if (!remotePath.startsWith(sep)) {
                remotePath = sep + remotePath;
            }

            //localPath & remotePath should both ends with / or not, otherwise the pathRewrite will
            //not work well
            if (remotePath.endsWith(sep) && !localPath.endsWith(sep)) {
                localPath = localPath + sep;
            }
            else if (!remotePath.endsWith(sep) && localPath.endsWith(sep)) {
                remotePath = remotePath + sep;
            }

            var pathRewrite = {};
            pathRewrite['^' + localPath] = remotePath; //^ is a symbol in regex, means beginning

            var proxy = proxyMiddleware(localPath, {
                target: serverAddr,
                changeOrigin: true, //needed for virtual hosted sites. Without this, proxy to
                                    //external sites will fail and are blocked by corp's internal
                                    //firewall
                pathRewrite: pathRewrite,
                secure: false //ignore verify SSL Certs, so proxy works for https
            });
            app.use(proxy);
            logger.info('Create proxy succeeded',
                {
                    localPath: localPath,
                    remotePath: remotePath,
                    serverAddress: serverAddr
                });
        }
        catch(e){
            logger.error('Create proxy failed',
                {
                    message: e.message,
                    parameter: httpProxy
                }
            );
        }
    }