vue项目配置多个Proxy代理

在Vue项目的开发过程中,为了本地调试方便,通常会在vue.config.js 中配置 devServer,实现本地启动一个服务器。在devServer中配置proxy属性,可以将指向本地的请求(例如: /api/action) 代理到后端的开发服务器上(例如: http://xxx.xxx.xxx/api/action)。

devServer: {
    
    
  disableHostCheck: true,//开启反向代理
  port: 8080,
  proxy: {
    
    
    '/api': {
    
    
      target: 'http://192.168.200.106:81',
      changeOrigin: true,// 默认情况下,代理时会保留主机头的来源,可以将 changeOrigin 设置为 true 以覆盖此行为,即:如果接口跨域,需要进行这个参数配置
      ws: false, // 是否代理websocket
      secure: false,// 忽略https安全提示(是否验证SSL Certs)。默认情况下,将不接受在 HTTPS 上运行且证书无效的后端服务器,如果要接受,可以设置secure: false
      pathRewrite: {
    
    
        '^/api': '/',// 替换前缀'/api',即:请求到 /api/xxx 现在会被代理到请求 http://192.168.200.106:81/xxx, 例如 /api/user 现在会被代理到请求 http://192.168.200.106:81/user
      }
    }
  }
},

1、接口地址有重叠地址时,将匹配度低的放在后面。例如:

  • 将 / 匹配到 192.191.1.1;
  • 将 /api 匹配到 192.191.1.2
  • 将 /api/action 匹配到 192.191.1.3

匹配规则是: 拿配置项中的地址去匹配请求中的地址,如果请求的地址中包含配置中的地址,则匹配成功,否则,拿下一个配置项继续匹配。
配置中的地址与请求地址中匹配的字符越少,则匹配度越低。上例配置中的地址(/)与请求地址(/api)只有一个字符是匹配的,所以匹配度低。

根据匹配规则,正确的写法是:

proxy: {
    
    
    '/api/action': {
    
    
        target: 'http://192.191.1.3',
        changeOrigin: true,
        ws: true,
        secure: false
    },
    '/api': {
    
    
        target: 'http://192.191.1.2',
        changeOrigin: true,
        ws: true,
        secure: false
    },
    '/': {
    
    
        target: 'http://192.191.1.1',
        changeOrigin: true,
        ws: true,
        secure: false
    }
}

2、多个地址代理同一个target 时,可进行合并
在实际应用中,由于后端采用微服务模式开发,在开发阶段,我们可能会将不同的服务代理到不同的地址上,当服务很多时,我们代理的数量也就很多。这个时候,可以对具有同一个target的配置项进行合并:

proxy: {
    
    
    '/api/action|/api/action2': {
    
    
        target: 'http://192.191.1.3',
        changeOrigin: true,
        ws: true,
        secure: false
    },
    '/api': {
    
    
        target: 'http://192.191.1.2',
        changeOrigin: true,
        ws: true,
        secure: false
    },
    '/': {
    
    
        target: 'http://192.191.1.1',
        changeOrigin: true,
        ws: true,
        secure: false
    },
}

注:在正式部署的时候,还是需要后端去做统一代理。

参考:
devServer.proxy
详解Webpack devServer的proxy用法

猜你喜欢

转载自blog.csdn.net/weixin_39964419/article/details/128092561
今日推荐