Search code examples
reactjsproxycross-domainhttp-proxy-middleware

Is there a way to call api with only different sub domains in React?


When I first did the React project, there was only one host domain api, so I used it by modifying the proxy value of the package file. (I prefer to use proxy because I suffered from cors problem.)

Recently, http-proxy-middleware was used to use more than two host domain api, and it has been used as follows.

module.exports = function(app){
    app.use(createProxyMiddleware('/call1', { target : 'http://sub.host1.com' }));
    app.use(createProxyMiddleware('/call2', { target : 'http://sub.host2.com' }));
    app.use(createProxyMiddleware('/call3', { target : 'http://sub.host3.com' }));
}  

The problem is that I want to call same API, but with only the sub domain differently, but I don't know how.

ex)

sub1.host1.com/call1

sub2.host1.com/call1

sub3.host1.com/call1

Please let me know if you have any idea. Thank you.


Solution

  • I hope this help.

    server.use(
      '/api',
      createProxyMiddleware({
        target: 'https://sub.domain.com/',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      })
    );