1

I'm trying to setup a proxy in express js, i am using http-proxy-middleware, it works perfect with hardcoded target.

server.use('/login', createProxyMiddleware({
 target: 'https://pretest.test.example',
 changeOrigin: true,
}))

in this case if i make a post request from my local domain (https://localhost:4200/login) it will proxy to https://pretest.test.example/login

but unfortunately its a multi site setup so i need the target to change based on the incoming request i have tried multiple ways but it doesnt seem to work.

server.use('/login', (req) => {
  createProxyMiddleware({
    target: resolveApiUrl(req),
    changeOrigin: true
  })
 })

 server.use('/login', createProxyMiddleware({
  target: '',
  changeOrigin: true,
  router: (req: string) => resolveApiUrl(req)
 }));

resolveApiUrl is just a function and takes the incoming request and formats the hostname to what i need it to be that works, also tried hardcoding values in the last 2 examples and that still doesnt work.

has anyone successfully managed to do dynamic targets based on incoming request with http-proxy-middleware?

Jake
  • 21
  • 3

1 Answers1

1

After creating the middleware, you must invoke it with all three arguments, req, res and next:

server.use('/login', function(req, res, next) {
  createProxyMiddleware({
    target: resolveApiUrl(req),
    changeOrigin: true,
  })(req, res, next);
});
Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31