How to work with multiple targets in webpack proxy?

Member

by brandy , in category: Javascript , 2 months ago

How to work with multiple targets in webpack proxy?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 2 months ago

@brandy 

To work with multiple targets in webpack proxy, you can use an object to specify multiple target URLs in the proxy configuration. Here's how you can set up multiple targets in webpack proxy:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
module.exports = {
  // other webpack configuration options

  devServer: {
    proxy: {
      '/api1': {
        target: 'http://localhost:3000',
        pathRewrite: { '^/api1': '' },
        changeOrigin: true,
      },
      '/api2': {
        target: 'http://localhost:4000',
        pathRewrite: { '^/api2': '' },
        changeOrigin: true,
      },
    },
  },
};


In this example, we have defined two proxy targets - one for requests to "/api1" and another for requests to "/api2". Requests to "/api1" will be proxied to http://localhost:3000, while requests to "/api2" will be proxied to http://localhost:4000.


You can define as many target URLs as needed in the proxy configuration object. Remember to set changeOrigin: true if you are proxying to a different domain to ensure that the origin header is correctly set in the proxied request.


You can test the proxy configuration by running your webpack dev server and sending requests to the specified endpoints. Make sure that the target servers are running and can handle the proxied requests.