Skip to content

Instantly share code, notes, and snippets.

@gouroujo
Created June 21, 2016 13:12
Show Gist options
  • Save gouroujo/a5d7d5582128d099cbfc5e826c55e311 to your computer and use it in GitHub Desktop.
Save gouroujo/a5d7d5582128d099cbfc5e826c55e311 to your computer and use it in GitHub Desktop.
Proxy on /api for express app using node http-proxy
import { createProxyServer } from 'http-proxy';
import url from 'url';
import _ from 'lodash';
module.exports = app => {
const proxy = createProxyServer();
app.all('/api/v1/*', (req, res) => {
const path = _.drop(req.url.split('/'), 3);
proxy.proxyRequest(req, res, {
target: url.resolve('YOUR URL', path.join('/')),
ignorePath: true,
headers: {
'Authorization': 'XXX)',
},
});
});
};
@dturton
Copy link

dturton commented Jul 21, 2017

how do you integrate this module to be used with express?

@geraldchecka
Copy link

import Express from 'express';
import path from 'path';
import { createProxyServer } from 'http-proxy';
import url from 'url';
import _ from 'lodash';

let
  app = Express(),
  appAPIProxy = createProxyServer();

/* App specific mounts */
app.use('/', Express.static(path.join(__dirname)));

app.all('/api/*', (req, res) => {
  const __path = _.drop(req.url.split('/'), 2);
  appAPIProxy.proxyRequest(req, res, {
    target: url.resolve('http://localhost', __path.join('/')),
    port: 8001,
    ignorePath: true
  });
});

appAPIProxy.on('proxyRes', function (proxyRes, req, res) {
  console.log("Response received");
});

appAPIProxy.on('error', function (err, req, res) {
  console.log("Error received");
});

app.listen(8010, function() {
  console.log("Listening on 8010");
})

@dturton This is the example in Express JS

@dandigangi
Copy link

Nice to see someone else using dangling commas :P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment