Skip to content

Instantly share code, notes, and snippets.

@iampeter
Last active April 14, 2020 13:00
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save iampeter/5af9c9e113e41c954364 to your computer and use it in GitHub Desktop.
Save iampeter/5af9c9e113e41c954364 to your computer and use it in GitHub Desktop.
Simple proxy with hapi.js to fix your CORS problems

Problem

While building a JavaScript single page app that acts as a front-end to multiple backend servers, even if they are on the same host as the web app - but on different ports, you come across CORS issues.

Solution

Use a simple node.js + hapi.js server to:

  1. Serve your static single page app
  2. Act as proxy to the backend servers

var Hapi = require('hapi');

var server = new Hapi.Server();
var remotes = [
  { url: "http://example.com:8080", path: 'server-1' },
  { url: "http://example.com:8081", path: 'server-2' },
  { url: "http://example-2.com", path: 'server-3' }
]

server.connection({ port: 80 });

remotes.forEach(function (remote) {
  server.route([
    {
      method: '*',
      path: '/' + remote.path + '/{params*}',
      handler: {
        proxy: {
          mapUri: function(request, callback) {
            var url = remote.url + "/" + request.url.href.replace('/' + remote.path + '/', '');
            callback(null, url);
          },
          passThrough: true,
          xforward: true
        }
      }
    }
  ]);
});

server.route({
  method: 'GET',
  path: '/{param*}',
  handler: {
    directory: {
      path: 'web',
      listing: true
    }
  }
});

server.start(function () {
  console.log('Server running at:', server.info.uri);
});


Now, assuming your static app is under /web, and is accessible at http://yourserver.com, you can call your backend servers as:

  • http://yourserver.com/server-1/whatever-server-1-requires
  • http://yourserver.com/server-2/whatever-server-2-requires
  • http://yourserver.com/server-3/whatever-server-3-requires
@Sitebase
Copy link

Sitebase commented Feb 17, 2017

Excellent suggestion!
Just as an addition for the people that want to use this: note that you have to install h2o2 module.

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