javascriptnode.jsexpresshttp-proxynode-http-proxy

Proxy multiple hosts that have same URL patterns


I am using http-proxy-middleware to proxy my API calls

How can I proxy multiple target hosts? I have searched through the issue and still could not understand.

https://github.com/chimurai/http-proxy-middleware/issues/12 - Allow me to use proxy table but what should link should I put for target? Because I have multiple targets.

I am thinking of pattern matching to proxy multiple hosts but another problem would arise because I have a few hosts with almost the same URL link.

Example

Tried some solutions below but dosen't work

Solution 1

const proxyOptions = proxy({
  target: ["https://website1.com", "https://website2.com", "https://api.website3.com"],
  changeOrigin: true,
  loglevel: "debug"
});

Solutuon 2

const proxyTable = {
  "/api": ["https://website1.com", "https://website2.com", "https://api.website3.com"]
};

const proxyOptions = proxy({
  target: "http://localhost:3000",
  router: proxyTable,
  changeOrigin: true,
  loglevel: "debug"
});

Solution 3

server.use(
      proxy("/api", { target: "https://website1.com", changeOrigin: true }),
      proxy("/api", { target: "https://website2.com", changeOrigin: true }),
      proxy("/api", { target: "https://api.website3.com", changeOrigin: true })
    );

Mounting the proxy

server.use("/api", proxyOptions)

Thanks for looking into this question!


Solution

  • I managed to get the solution using pathRewrite

    const website1 = proxy({
      target: "https://website1.com",
      changeOrigin: true,
      pathRewrite: {
        "^/website1": "/api"
      },
      loglevel: "debug"
    });
    
    const website2 = proxy({
      target: "https://website2.com",
      changeOrigin: true,
      pathRewrite: {
        "^/website2": "/api"
      },
      loglevel: "debug"
    });
    
    const website3 = proxy({
      target: "https://api.website3.com",
      changeOrigin: true,
      pathRewrite: {
        "^/website3": "/api"
      },
      loglevel: "debug"
    });
    

    Mounting the server

    const server = express();
    
    server.use("/website1", website1);
    server.use("/website2", website2);
    server.use("/website3", website3);
    

    However, this will give my website alot pages that I do not need like http://localhost:3000/website1 and etc.

    Are there any ways to hide these pages or display something else instead of the homepages of websites that I am using.

    Sorry, I am still learning node.js please be patience with me.