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

To help you get started, we’ve selected a few express-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 opencollective / opencollective-frontend / src / server / routes.js View on Github external
});

  // Support older assets from website
  server.use('/public/images', express.static(path.join(__dirname, '../static/images')));

  server.get('/static/*', maxAge(7200));

  server.get('/favicon.*', maxAge(300000), (req, res) => {
    return res.sendFile(path.join(__dirname, '../static/images/favicon.ico.png'));
  });

  // NOTE: in production and staging environment, this is currently not used
  // we use Cloudflare workers to route the request directly to the API
  server.use(
    '/api',
    proxy(getBaseApiUrl({ internal: true }), {
      parseReqBody: false,
      proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
        proxyReqOpts.headers['oc-frontend-api-proxy'] = '1';
        proxyReqOpts.headers['oc-frontend-ip'] = srcReq.ip;
        proxyReqOpts.headers['X-Forwarded-For'] = srcReq.ip;
        return proxyReqOpts;
      },
      proxyReqPathResolver: req => {
        const [pathname, search] = req.url.split('?');
        const searchParams = new URLSearchParams(search);
        searchParams.set('api_key', process.env.API_KEY);
        return `${pathname.replace(/api/, '/')}?${searchParams.toString()}`;
      },
    }),
  );
github aolarchive / chronos / ui / webpack.js View on Github external
// config

const server = new WebpackDevServer(webpack(config), {
  publicPath: config.output.publicPath,
  contentBase: './public',
  hot: true,
  historyApiFallback: true,
  quiet: false,
  noInfo: true,
  stats: {
    colors: true,
  },
});

if (process.env.CHRONOS_PROXY_URL) {
  server.use('/api', proxy(process.env.CHRONOS_PROXY_URL, {
    forwardPath(req) {
      return '/api' + url.parse(req.url).path;
    },
  }));
}

// run

server.listen(8000, 'localhost', (err) => {
  console.log(err || 'Listening at localhost:8000');
});
github bananaoomarang / chapters / server.jsx View on Github external
combineReducers,
         applyMiddleware }       from 'redux';

const API_URL = 'http://localhost:8888';

// Prepend all axios requests with API address
axios.interceptors.request.use( (cfg) => {
  cfg.url = API_URL + cfg.url;

  return cfg;
});

const app = express();

// Proxy to API
app.use('/api', proxy(API_URL));

if (process.env.NODE_ENV !== 'production')
  webpackDev(app);

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

const routes = createRoutes(function (nextState, transition, done) { done(); });

// Pass everything else through react-router
app.use(function (req, res) {
  const reducer  = combineReducers(reducers);
  const store    = applyMiddleware(promiseMiddleware)(createStore)(reducer);

  match({ routes, location: req.url }, (routeErr, redirectLocation, renderProps) => {
    if(routeErr) {
      console.error(routeErr);
github WaftTech / WaftEngine / ssr-client / src / index.js View on Github external
import Routes from './client/Routes';
import renderer from './helpers/renderer';
import createStore from './helpers/createStore';

const app = express();

const port = process.env.PORT || 5013;

export const API_URL = 'https://api.ask4trip.in';

app.use(expressip().getIpInfoMiddleware);

app.use(
  '/api',
  proxy(API_URL, {
    proxyReqOptDecorator(opts) {
      opts.headers['x-forwarded-host'] = 'localhost:5010'; // eslint-disable-line no-param-reassign
      return opts;
    },
  }),
);
app.use(express.static('public'));
app.get('*', (req, res) => {
  res.set('Cache-Control', 'public, max-age=60');
  const store = createStore(req);
  if (req.ipInfo.ll && req.ipInfo.ll.length === 2) {
    store.dispatch({ type: 'SET_LATITUDE', payload: req.ipInfo.ll[0] });
    store.dispatch({ type: 'SET_LONGITUDE', payload: req.ipInfo.ll[1] });
  }

  const promises = matchRoutes(Routes, req.path)
github EYBlockchain / nightfall / api-gateway / src / index.js View on Github external
authentication, // Authorization filter to verify Role of the user
  unlockAccount,
  formatResponse,
  formatError,
  errorHandler,
} from './middlewares';

const app = express();
const router = Router();

app.use(bodyParser.json()); // set up a filter to parse JSON

app.use(cors()); // cross origin filter
app.use(authentication);

app.use('/zkp', unlockAccount, proxy(config.zkp.url));

app.use('/', unlockAccount, router);
app.use('/', rootRouter);
app.use('/token', nftCommitmentRoutes);
app.use('/coin', ftCommitmentRoutes);
app.use('/ft', ftRoutes);
app.use('/nft', nftRoutes);
app.use('/user', userRoutes);
app.use('/shield', shieldRoutes);

app.use(formatResponse);

app.use(function logError(err, req, res, next) {
  if (err instanceof Error) {
    logger.error(
      `${req.method}:${req.url}
github robinweser / fela / examples / react / server.js View on Github external
import express from 'express'
import proxy from 'express-http-proxy'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-fela'
import fs from 'fs'

import App from './app.js'
import createRenderer from './renderer'

const app = express()

app.use(
  '/bundle.js',
  proxy('localhost:8080', { forwardPath: () => '/bundle.js' })
)

app.get('/', (req, res) => {
  const renderer = createRenderer()

  const indexHTML = fs.readFileSync(`${__dirname}/index.html`).toString()
  const appHtml = renderToString(
    
      
    
  )
  const appCSS = renderer.renderToString()
  const fontCSS = renderer.fontRenderer.renderToString()

  res.write(
    indexHTML
github resistdesign / rdx / src / Commands / Serve.jsx View on Github external
noInfo: true,
      watchOptions: {
        aggregateTimeout: 300,
        poll: 500
      },
      stats: {
        colors: true
      },
      historyApiFallback: true,
      disableHostCheck: true
    });

    if (typeof proxy === 'string') {
      this.log('Proxy', 'Forwarding all unresolved requests to', proxy);

      server.use(Proxy(proxy, {limit: '8gb'}));
    }

    this.log('Server', 'Starting', '...');

    await new Promise((res, rej) => {
      server.listen(port, host, error => {
        if (error) {
          rej(error);
        }

        this.log('Server', 'Running on:', hostedUrl);

        compiling = true;
        compileStartTime = new Date().getTime();
        this.log('Start', 'Compiling', '...');
github alexolefirenko / react-admin-ui / server / server.js View on Github external
if (global.Intl) {
    if (!areIntlLocalesSupported(nodeLocales)) {
        require('intl')
        Intl.NumberFormat = IntlPolyfill.NumberFormat;
        Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
    }
} else {
    global.Intl = require('intl');
}

app.use(cookieParser())
app.use('/public', express.static(resolve(__dirname, '../public')))
app.get('/favicon:ext', (req, res)=> {
    res.sendFile(resolve(__dirname, `../assets/favicon${req.params.ext}`))
})
app.use('/uploads', proxy(origin, {
    forwardPath: (req)=> {
        return '/uploads' + require('url').parse(req.url).path
    }
}))

app.use((req, res)=> {
    const store = configureStore()
    match({routes, location: req.url}, (err, redirect, renderProps)=> {
        if (err) {
            res.status(500).send('Internal error :(')
        } else if (redirect) {
            res.redirect(302, redirect.pathname + redirect.search)
        } else if (renderProps) {
            store.dispatch(setUserAgent(req.get('user-agent')))
            store.dispatch(setLocale(req.cookies.locale || defaultLocale))
            const unplug = plugToRequest(req, res)
github robinweser / fela / examples / example-preact / server.js View on Github external
import express from 'express'
import proxy from 'express-http-proxy'
import { h } from 'preact'
import render from 'preact-render-to-string'
import { Provider } from 'preact-fela'
import { renderToMarkup } from 'fela-dom'
import fs from 'fs'
import App from './app.js'
import createRenderer from './renderer'

const app = express()

app.use('/bundle.js', proxy('localhost:8080', { forwardPath: () => '/bundle.js' }))

app.get('/', (req, res) => {
  const renderer = createRenderer()

  const indexHTML = fs.readFileSync(`${__dirname}/index.html`).toString()
  const appHtml = render(
    
      
    
  )
  const appCSS = renderToMarkup(renderer)

  res.write(indexHTML.replace('', appHtml).replace('', appCSS))
  res.end()
})
github TradeMe / tractor / plugins / mock-requests / src / protractor / server.js View on Github external
const port = await getPort();
    mockRequestsConfig.port = port;

    shimZlib();

    let application = express();

    let host = baseUrl;
    server = http.createServer(application);

    application.use(bodyParser.json());
    application.set('etag', false);

    application.use('/mock-requests/add-mock', addMock);

    application.use(proxy(host, {
        proxyReqOptDecorator: createRequestDecorator(host, mockRequestsConfig),
        userResDecorator: createResponseDecorator(host)
    }));

    return new Promise(resolve => {
        server.listen(port, () => {
            info(`@tractor-plugins/mock-requests is proxying at port ${port}`);
            resolve();
        });
    });
}

express-http-proxy

http proxy middleware for express

MIT
Latest version published 5 months ago

Package Health Score

79 / 100
Full package analysis

Popular express-http-proxy functions