I am trying to get http-proxy-middleware working, what I am trying to achieve is having multiple nodejs apps running and then having the proxy app as a reverse proxy server.
The problem I encounter is when I press a link on a proxied app, here's my code:
var express = require('express')
var proxy = require('http-proxy-middleware')
var app = express()
var options = {
target: 'http://localhost:1001', // target host
changeOrigin: true, // needed for virtual hosted sites
ws: false, // proxy websockets
logLevel: "debug",
pathRewrite: {
'^/foo': '/', // rewrite path
}
}
var exampleProxy = proxy(options)
app.use('/foo', exampleProxy)
app.listen(3000)
On the localhost:1001 app I got the routes '/' and '/bar'
app.get('/', function (req, res) {
res.render('home');
});
app.get('/bar', function (req, res) {
res.render('bar');
});
If I go to localhost:3000/foo it will reroute me to localhost:1001/ (while showing localhost:3000/ in the browser) and the same with localhost:3000/foo/bar. So this works fine.
The problem happens when I go to localhost:3000/foo and then press the link to 'bar', it will then route me to localhost:3000/bar which is not a route I have defined in my proxy server.
So what I need is that when I press on the link to /bar it will route it to /foo/bar in the proxy.
I have tried coming up with some ways to fix this, but have (obviously) not been succesful:
Add the port (1001) to the response (res.locals.portNo = "1001") and then send that in the request so that the proxy can check where the request is coming from and add /foo (if its 1001). (I have not tried this yet, but maybe this could be achieved by using cookies?)