Vue中配置axios跨域多个proxyTable代理

vue.config.js

配置参考:https://cli.vuejs.org/config/#devserver-proxy

devServer: {
  open: true,
  port: 8081,
  proxy: {
    //匹配/gw1-api开头的请求
    [process.env.VUE_APP_GW1_BASE_API]: {
      //目标服务器,代理访问到https://localhost:8080
      target: process.env.VUE_APP_GW1_URL,
      // 开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,
      // 并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
      changOrigin: true, //开启代理
      pathRewrite: {
        // 会将 /gw1-api 替换为 '',也就是 /gw1-api 会移除,
        // 如 /gw1-api/db.json 代理到 https://localhost:8080/db.json
        // '^/gw1-api': "",
        ["^" + process.env.VUE_APP_GW1_BASE_API]: ""
      }
    },
    //匹配/gw2-api开头的请求
    [process.env.VUE_APP_GW2_BASE_API]: {
      //目标服务器,代理访问到https://localhost:8080
      target: process.env.VUE_APP_GW2_URL,
      // 开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,
      // 并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
      changOrigin: true, //开启代理
      pathRewrite: {
        // 会将 /gw2-api 替换为 '',也就是 /gw2-api 会移除,
        // 如 /gw2-api/db.json 代理到 https://localhost:8080/db.json
        // '^/gw2-api': "",
        ["^" + process.env.VUE_APP_GW2_BASE_API]: ""
      }
    },
  }
},

.env

# 使用 VUE_APP_ 开头的变量会被 webpack 自动加载
# 定义请求的基础URL, 方便跨域请求时使用

VUE_APP_GW1_BASE_API = '/gw1-api'
VUE_APP_GW2_BASE_API = '/gw2-api'

# 接口服务地址(网关地址)
# 可更改为自已配置的 Easy-Mock 接口服务地址

VUE_APP_GW1_URL = 'http://192.168.1.10:8001/gateway'
VUE_APP_GW2_URL = 'http://192.168.1.10:8002/gateway'

api

export function test1(data) {
  return request({
    url: '/gw1-api/test1',
    method: 'post',
    data,
  });
}
export function test2(data) {
  return request({
    url: '/gw2-api/test2',
    method: 'post',
    data,
  });
}
上一篇 Vue proxyTable build打包后访问报404
下一篇 VuePress技术笔记站点部署
目录
文章列表
1 Android 10(Api 29)新特性适配 - 后台应用增加定位限制
Android 10(Api 29)新特性适配 - 后台应用增加定位限制
2
让新版Appium支持ByName定位
让新版Appium支持ByName定位
3
MyBatis mybatis-generator自定义plugin
MyBatis mybatis-generator自定义plugin
4
C++ ANSI及UTF-8与Unicode转码
C++ ANSI及UTF-8与Unicode转码
5
Android NDK基础21:C++_继承_多态
Android NDK基础21:C++_继承_多态
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。