2

This is for a NodeJS, Express application.

I want to take a request coming into a path like https://mycompany.com/cost-recovery -> http://mycompany.com:8447/cost-recovery. I wish to pass all headers, request bodies, etc. over to this forwarded host. Essentially the only thing I'm doing is changing the port.

I looked at http-proxy-middleware, but wasn't sure how to approach this. I wasn't sure what the router option does. Also, if there are any query strings I'm not sure they'll get passed. The problem with this service is that it doesn't look like I can take an incoming request and generate the proxy. Or at least, I don't know how. If I could, I'd build the proxy as a handler based on the incoming request.

Not looking for a full coding snippet, just a clue on what section to look for. Or if you do have an example, I'd like to see it.

Woodsman
  • 901
  • 21
  • 61

1 Answers1

1

As you suspected using the router allows you to control how/where to proxy the request to. Note that the target is not needed in this case, but you need to specify it anyway, as the lib will throw an error otherwise (see this github-issue where this is discussed).

So, if for example you want to control where to proxy to based on the request-path, you can do the following:

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const proxyMiddleware = createProxyMiddleware({
target: 'not-needed',
router: (req) => {
    if (req.path === '/cost-recovery') {
        return 'http://some-domain:1234';
    } else if (req.path === '/some-other-path') {
        return 'http://some-domain.com:5678';
    }
  }
});

const app = express();

app.use(proxyMiddleware);

app.listen(3000); // set whatever port your proxy-app should run on here
eol
  • 23,236
  • 5
  • 46
  • 64
  • I like the simplicity, but I can't be certain what the host name is or the query strings. This could be deployed on a test system with a different host name. – Woodsman Dec 22 '20 at 15:02
  • If you want to proxy all requests regardless of the actual route, you can just remove the `/cost-recovery` context: `app.use(proxyMiddleware);` Also you can specify the router to control where to proxy to. Please, check my edit :) – eol Dec 22 '20 at 15:33
  • I don't want to proxy all requests, those that I proxy would go to different ports (they're actually reaching different Angular containers). – Woodsman Dec 22 '20 at 17:40
  • 1
    Above code proxies only requests with path `/cost-recovery` to `some-domain.com:1234` and requests with path `/some-other-path` to `some-domain.com:5678`.Isn't that what you need? – eol Dec 23 '20 at 07:12