4

I'm running an Angular Universal application that is talking to an API. Now I'm trying to set up a proxy in the Universal server that proxies API requests to the actual API server:

  server.use(['/api', '/sitemap.txt'], createProxyMiddleware({
    target: process.env.API_URL,
    onProxyReq: req => {
      console.log('Using origin: ' + getOrigin(req.getHeaders()));
      req.setHeader('origin', getOrigin(req.getHeaders()));
    },
    pathRewrite: {'^/api': ''}
  }));

This works perfectly when running locally, but when running it on the server (Azure WebApp), it doesn't work. I can see the console log being called in the WebApp logs, but the resulting document is the Angular application with a message "page not found".

I'm totally out of ideas on where to look for solutions.

Edit:

I tried another proxy middleware and it does do the trick. This code works both locally and on Azure.


import * as proxy from 'express-http-proxy';

// ...

  server.use(['/api', '/sitemap.txt'], proxy(process.env.API_URL, {
    proxyPathResolver: req => {
      let url: string = req.url;

      if (url.startsWith('/api')) {
        url = url.substr(4);
      }

      return url;
    },

    proxyReqOptDecorator(proxyReqOpts, srcReq) {
      proxyReqOpts.headers['origin'] = getOrigin(proxyReqOpts.headers);
      return proxyReqOpts;
    }
  }));

But it has some other limitations that make it unusable for our project, so I still need this resolved.

Bart van den Burg
  • 2,166
  • 4
  • 25
  • 42

1 Answers1

0

I have it working correctly now. This is the current setup:

  server.use(
    '/api',
    createProxyMiddleware({
      target: process.env.API_URL,
      changeOrigin: true,
      headers: {
        Connection: 'keep-alive',
      },
      onProxyReq: (proxyReq, req, _res) => {
        proxyReq.setHeader('origin', getOrigin(req.headers));
      },
      pathRewrite: {
        '^/api': '',
      },
    })
  );

So I added changeOrigin and the keep-alive header. I'm not sure which of the two resolved the issue, once I got it to work I never bothered to check it out. I suspect it's the header, though.

Bart van den Burg
  • 2,166
  • 4
  • 25
  • 42