关于项目中配置多个代理的问题

162 阅读1分钟
 devServer: {
        // 使用代理进行解决跨域的问题
        proxy: {
            '/api': {
                target: 'http://xxx.xx.xxx.xxx:9006/',
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/api': '/api'
                }
            },
            '/opdaeng': {
                target: 'http://xxx.xx.xxx.xxx:9086/',
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/opdaeng': '/opdaeng'
                }
            },
        }
    }
  • 当我们在项目中需要请求不同的域名与端口号时,可以通在proxy中设置代理来解决。 接口地址有重叠地址时,将匹配度低的放在后面。

  • 比如下面这样

    
    proxy: {
              '/': {
                  target: 'http://192.168.1.1',
                  changeOrigin: true,
                  ws: true,
                  secure: false
              },
      		 '/api': {
                  target: 'http://192.168.1.2',
                  changeOrigin: true,
                  ws: true,
                  secure: false
              },
      		 '/api/action': {
                  target: 'http://192.167.1.3',
                  changeOrigin: true,
                  ws: true,
                  secure: false
              }
          }
          那么所有到/, /api和 /api/action 的请求将全部被代理到 192.191.1.1 上面去
    

原因是这里的匹配实际上是一个正则匹配的过程,当我们请求 /api 时,首先读取到了配置项中的第一个,拿配置中的 / 去匹配请求中的 /api , 发现请求的/api 中包含配置项/, 匹配成功,直接将请求代理到了 192.191.1.1 上面去, 对/api/action的匹配也同理。

  • 正确写法如下
proxy: {
            '/api/action': {
                target: 'http://192.168.1.3',
                changeOrigin: true,
                ws: true,
                secure: false
            },
            '/api': {
                target: 'http://192.168.1.2',
                changeOrigin: true,
                ws: true,
                secure: false
            },
            '/': {
                target: 'http://192.168.1.1',
                changeOrigin: true,
                ws: true,
                secure: false
            }
        }