browser-synchttp-proxy-middlewarelite-server

http-proxy-middleware: pathFilter not working as expected


I am trying so setup a npm-based HTML development environment using two servers. One hosts my HTML app of static files (standard way: http://localhost:8080) while the other exposes an application api running locally(http://127.0.0.1:57146/api/someEntity). The latter is beyond my control. Calling the api URLs directly from my app brings up CORS issues. So i want to setup a proxy that redirects my calls from http://localhost:8080/apiBase/someEntity to http://127.0.0.1:57146/api/someEntity... hoping to avoid the CORS problems that way.

I am using lite-server, which builds on top of Browsersync.

Since my static app files do not need redirection, they should not be affected by the proxy.
To specify, which calls are redirected, i am trying to use the "pathFilter" field in the options. But i cannot get that functioning. Instead all calls are always proxied to http://127.0.0.1:57146. "pathRewrite" does not seems to work, either. So it seems like i am missing something basic here. What am i doing wrong?

Here is my config file:

//bs-config.cjs

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

const apiProxy = createProxyMiddleware({
  target: "http://127.0.0.1:57146/",
  pathFilter:"apiBase/",
  pathRewrite: {
    "apiBase/": "api/"
  },
  logger: "console",
  logLevel: "debug"
});

module.exports = {
  port: 8080,
  index: "parent.htm",
  startPath: "parent.htm",
  cors: true,
  server: {
    baseDir: "./dist",
    index: "parent.htm",
    cors: true,
    middleware: [ apiProxy ]      
  }
};

Solution

  • With the help of a (very) patient backend guy, i finally found a solution. We could not get "pathRewrite" to work, but after getting the filter functioning (by changing some syntax), tweaking the paths ended up in a working setup.

    //bs-config.cjs
    
    const { createProxyMiddleware } = require('http-proxy-middleware');
    
    const proxy_filter = function (path, req) {
      const regx = new RegExp("/apiBase");
      return path.match(regx);
    };
    
    const proxy_options = {
      target: "http://127.0.0.1:57146/api/",
      changeOrigin: true,  
      logger: "console",
      logLevel: "debug"
    }
    
    const apiProxy = createProxyMiddleware(proxy_filter, proxy_options);
    
    module.exports = {
      port: 8080,
      index: "parent.htm",
      startPath: "parent.htm",
      server: {
        baseDir: "./dist",
        index: "parent.htm",
        middleware: [
          apiProxy
        ]
      }
    };