cucucool
cucucool

Reputation: 3887

NodeJS HTTP proxy - Add a header and update the request URL

I am using this module to do the following:

  1. Parse the req URL
  2. Add a new header to the request using the token from the URL
  3. Update the actual request URL (remove the token from the URL)

I am trying to do that with the following code:

function initializeServer(){
  var server = app.listen(5050, function () {
    var host = server.address().address
    var port = server.address().port
    logger.info('NodeJS Server listening at http://%s:%s', host, port)
  });
}

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  console.log("intercepting ... ")
    proxyReq.setHeader('x-replica', '123');
    req.url = '/newurl';
});

function initializeController(){
  app.get('/myapp*', function (req, res) {
     proxy.web(req, res, { target: 'http://127.0.0.1:8081' });
  });
}

where 8081 is my test server and proxy server runs at 5050.

Now, the header setting works but the setting the URL does not. How to achieve this with node HTTP proxy ?

Upvotes: 1

Views: 3216

Answers (1)

keithmo
keithmo

Reputation: 4943

In the proxy.on('proxyReq',...) handler req is the (original) incoming request, while proxyReq is the request that will be issued to the target server. You need to set the proxyReq.path field.

Upvotes: 2

Related Questions