How to use http-proxy-middleware - 10 common examples

To help you get started, we’ve selected a few http-proxy-middleware 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 replicatedhq / kots / api / src / update / proxy.ts View on Github external
import { IncomingMessage } from "http";
import proxyMiddleware from "http-proxy-middleware";
import { parse } from "url";
import { logger } from "../server/logger";

export const UpdateProxy = proxyMiddleware({
  target: "Ship Cloud Binary - Update",
  proxyTimeout: 5000,
  router(req: IncomingMessage): string {
    if (!req.url) {
      throw new Error("Invalid URL");
    }
    const { pathname = "" } = parse(req.url);
    const splitPath = pathname.split("/");
    const [, , , , updateId] = splitPath;

    // tslint:disable-next-line:no-http-string
    const shipUpdateInstanceHost = `http://shipupdate-${updateId}.shipupdate-${updateId}.svc.cluster.local:8800`;

    return shipUpdateInstanceHost;
  },
  pathRewrite(path: string): string {
github vendure-ecommerce / vendure / server / src / plugin / plugin-utils.ts View on Github external
export function createProxyHandler(options: ProxyOptions, logging: boolean) {
    const route = options.route.charAt(0) === '/' ? options.route : '/' + options.route;
    const proxyHostname = options.hostname || 'localhost';
    return proxy({
        // TODO: how do we detect https?
        target: `http://${proxyHostname}:${options.port}`,
        pathRewrite: {
            [`^${route}`]: `/`,
        },
        logLevel: logging ? 'info' : 'silent',
    });
}
github geelen / react-snapshot / src / Server.js View on Github external
next()
    })

    // Yes I just copied most of this from react-scripts ¯\_(ツ)_/¯
    app.use(publicPath,
      historyApiFallback({
        index: '/200.html',
        disableDotRule: true,
        htmlAcceptHeaders: ['text/html'],
      }),
      express.static(baseDir, { index: '200.html' })
    )

    if (proxy) {
      if (typeof proxy !== "string") throw new Error("Only string proxies are implemented currently.")
      app.use(httpProxyMiddleware({
        target: proxy,
        onProxyReq: proxyReq => {
          if (proxyReq.getHeader('origin')) proxyReq.setHeader('origin', proxy)
        },
        changeOrigin: true,
        xfwd: true,
      }))
    }

    this.start = this.start.bind(this, app, port)
  }
github pingcap / tidb-dashboard / ui / src / setupProxy.js View on Github external
module.exports = function (app) {
  // Proxy the `data.js` trick to the backend server.
  // Proxy http://localhost:3001/dashboard/api/diagnose/reports/*/data.js to
  // http://http://127.0.0.1:12333/dashboard/api/diagnose/reports/*/data.js
  app.use(
    '/',
    createProxyMiddleware('/dashboard/api/diagnose/reports/*/data.js', {
      target: dashboardApiPrefix,
      changeOrigin: true,
    })
  )

  // Rewrite the webpage to our static HTML.
  // Rewrite http://localhost:3001/dashboard/api/diagnose/reports/*/detail
  // to http://localhost:3001/dashboard/diagnoseReport.html
  app.use('/dashboard/api/diagnose/reports/:id/detail', function (req, res) {
    req.url = paths.publicUrlOrPath + 'diagnoseReport.html'
    app.handle(req, res)
  })
}
github dotnetcore / WTM / demo / WalkingTec.Mvvm.Next / ClientApp / packages / www-react / src / setupProxy.js View on Github external
module.exports = (app) => {
    app.use(proxy('/api', {
        // target: 'http://118.178.132.249:7778/',
        target: 'http://localhost:5555/',
        changeOrigin: true,
        logLevel: "debug"
    }));
    // mock(app);
};
github pennlabs / penn-courses / frontend / alert / server.js View on Github external
Object.keys(devProxy).forEach(function(context) {
                    server.use(
                        createProxyMiddleware(context, devProxy[context])
                    );
                });
                /* eslint-enable */
github AdguardTeam / AdGuardHome / client2 / scripts / webpack / webpack.config.dev.js View on Github external
const { merge } = require('webpack-merge');
const path = require('path');
const proxy = require('http-proxy-middleware');
const Webpack = require('webpack');

const { getDevServerConfig } = require('./helpers');
const baseConfig = require('./webpack.config.base');

const devHost = process.env.DEV_HOST
const target = getDevServerConfig();

const options = {
    target: devHost || `http://${target.host}:${target.port}`, // target host
    changeOrigin: true, // needed for virtual hosted sites
};
const apiProxy = proxy.createProxyMiddleware(options);

module.exports = merge(baseConfig, {
    mode: 'development',
    output: {
        path: path.resolve(__dirname, '../../build2'),
        filename: '[name].bundle.js',
    },
    optimization: {
        noEmitOnErrors: true,
    },
    devServer: {
        port: 4000,
        historyApiFallback: true,
        before: (app) => {
            app.use('/control', apiProxy);
            app.use(history({
github nuxt-community / modules / packages / proxy / index.js View on Github external
proxy.forEach(args => {
    const middleware = Proxy.apply(undefined, args)
    middleware.prefix = false // Don't add router base
    this.options.serverMiddleware.push(middleware)
  })
}
github nuxt-community / proxy-module / lib / module.js View on Github external
proxy.forEach((args) => {
    // https://github.com/chimurai/http-proxy-middleware
    const middleware = Proxy.apply(undefined, args)
    middleware.prefix = false // Don't add router base
    this.addServerMiddleware(middleware)
  })
}
github react-zeroconfig / react-zeroconfig / src / utils / web / createBrowserSyncConfig.ts View on Github external
const middleware: (MiddlewareHandler | PerRouteMiddleware)[] = [
    webpackDevMiddleware(compiler, {
      publicPath: app.publicPath,
      stats: {colors: true},
    }),
    
    webpackHotMiddleware(compiler),
    
    compression(),
    
    ...middlewares,
  ];
  
  if (serverEnabled) {
    middleware.push(
      proxyMiddleware(['**', '!**/*.*'], {
        target: `http://localhost:${app.serverPort}`,
      }),
    );
  } else {
    middleware.push(
      function (req: IncomingMessage, res: ServerResponse, next: () => void) {
        if (req.url && !/\.[a-zA-Z0-9]+$/.test(req.url)) {
          req.url = '/index.html';
        }
        return next();
      },
    );
  }
  
  return Promise.resolve({
    port: app.port,

http-proxy-middleware

The one-liner node.js proxy middleware for connect, express, next.js and more

MIT
Latest version published 1 month ago

Package Health Score

91 / 100
Full package analysis