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.
Use a simple node.js + hapi.js server to:
- Serve your static single page app
- 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
Excellent suggestion!
Just as an addition for the people that want to use this: note that you have to install h2o2 module.