In order to avoid the typical CORS problem with client-side javascript code I use a nodejs express server. This server contains the following code:
var app = express();
app.all('/Api/*', function (req, res) {
proxy.web(req, res, {
target: 'https://www.myserver.com',
changeOrigin:true
});
});
So what this does is redirect any call that starts with /Api
to my server.
However, this also appends Api
to the url path, so Api/getData
becomes https://www.myserver.com/Api/getData
Is there way to strip the Api
part of the relative url? The end result would be Api/getData
becoming https://www.myserver.com/getData
This would allow me to target several servers by changing the first part of the relative url path. Something like this:
Api/getData
-> https://www.myserver.com/getData
OtherApi/getData/for/some/path
-> https://www.some-other-server.com/getData/for/some/path
This should of course work for all request types, not only for GET
Thanks!
Take a look at the http-proxy-rules module, which is a companion module for node-http-proxy. It allows you to write rules for changing matching routes to different proxy routes.
With it you should be able to define your translations like this:
var proxyRules = new HttpProxyRules({
rules: {
'.*/Api': 'http://myserver.com/', // Rule (1)
'.*/OtherApi*': 'http://some-other-server.com:8080/' // Rule (2)
},
default: 'http://myserver.com/' // default target
});
Then use them like this:
app.all('*', function(req, res) {
var target = proxyRules.match(req);
if (target) {
return proxy.web(req, res, {
target: target
});
}
})