Search code examples
node.jsexpressnpmhttp-proxy

How to Proxy using Node using express-http-proxy to strip final rest


On my local JavaScript, I want to make a rest call to

/rest/speakers

and have that proxied to

http://localhost:2011/rest/speakers

I have code as follows that does not quite work as I want:

var proxy = require('express-http-proxy');
var app = require('express')();
app.use('/rest', proxy('localhost:2011/'));
app.listen(8081, function () {
    console.log('Listening on port 8081');
});

To make the proxy work, I actually need to call

/rest/rest/speakers

I kind of get it. It seems that I'm proxying my /rest to the root of localhost:2011 and then I need to dive into the /rest of that server. Adding /rest to the end of the proxy(..) is ignored.


Solution

  • Try using proxyReqPathResolver to modify your URL as needed.

    var url = require('url'),
        proxy = require('express-http-proxy');
    
    // ... other app setup here 
    
    app.use('/rest', proxy('localhost:2011', {
        proxyReqPathResolver: function(req, res) {
          return '/rest/rest' + url.parse(req.url).path;
        }
    }));