proxy反向代理解决跨域问题

1.vue本地开发解决跨域问题

  • webpack 提供一个本地的服务器,通过如下配置解决本地开发跨域问题
modul.exports = defineConfig({
	configureWebpack:{
	devServer: {
      host: "localhost",
      port: "8181",
      open:true,
      proxy: {
        '/api1': {
          target: process.env.VUE_APP_BASE_API1,
          secure:true,//接受对方是https的接口
          changeOrigin: true,//需要跨域
        },
        '/api2': {
          target: process.env.VUE_APP_BASE_API2,
          secure:true,//接受对方是https的接口
          changeOrigin: true,//需要跨域
        },
        '/api3': {
          target: process.env.VUE_APP_BASE_API3,
          secure:true,//接受对方是https的接口
          changeOrigin: true,//需要跨域
        },
        '/api4': {
          target: process.env.VUE_APP_BASE_API4,
          secure:true,//接受对方是https的接口
          changeOrigin: true,//需要跨域
        },
      }
    },
	}
})

2. proxy 实现反向代理

  • 项目打包部署后,需要使用proxy转发请求
  • 如下代码所示,location 后面跟的是请求路径,例如请求路径为’localhost:8181/api1/getuser’, proxy 会将请求由当前域名代理到 ‘https://test-uhihi.fake1.com’;最终请求的地址为 ‘https://test-uhihi.fake1.com/api1/getuser’
location / {
  # root   html;
  index  index.html index.htm;
  # 解决SPA导致的刷新报404问题
  try_files $uri $uri/ /index.html;
}
location /api1 {
	proxy_pass https://test-uhihi.fake1.com;
}
location /api2 {
	proxy_pass https://test-uhihi.fake2.com;
}
location /api3 {
	proxy_pass https://test-uhihi.fake3.com;
}
location /api4 {
	proxy_pass https://test-uhihi.fake4.com;
}

3 将代理配置文件复制到dist中

  • 我们老大要求我直接把代理配置放在json文件里给运维,预防以后域名变更运维还要再改一次。
  • 我在根目录下创建了一个 proxy 文件夹,分别存着testProxy.json,betaProxy.json,prodProxy.json
  • testProxy.json 配置文件如下,其它两个修改成对应地址即可
[
  {
    "location":"/api1",
    "proxy_pass":"https://test-uhihi.fake1.com"
  },
  {
    "location":"/api2",
    "proxy_pass":"https://test-uhihi.fake2.com"
  },
  {
    "location":"/api3",
    "proxy_pass":"https://test-uhihi.fake3.com"
  },
  {
    "location":"/api4",
    "proxy_pass":"https://test-uhihi.fake4.com"
  },
]
3.1 使用 copy-webpack-plugin 在打包时自动将配置文件放到dist文件夹中

安装 copy-webpack-plugin 插件

npm i -D copy-webpack-plugin

在vue.config.js中使用插件

//1 引入插件copy-webpack-plugin
const CopyWebpackPlugin = require('copy-webpack-plugin')
//2 根据模式打包获取对应配置文件路径
let proxyFile = ''
switch (process.env.VUE_APP_VERSION_TYPE) {
  case "Test Version":
    proxyFile = './proxy/testProxy.json'
    break;
  case "Official Version":
    proxyFile = './proxy/prodProxy.json'
    break;
  case "Beta Version":
    proxyFile = './proxy/betaProxy.json'
    break;
}
const plugin = [
	new CopyWebpackPlugin({
    patterns:[
      {
        from: proxyFile, to: 'proxy.json'//统一名称proxy.json
      }
  ]})
]
modul.exports = defineConfig({
	configureWebpack:{
	plugins:plugins,
	}
})

打包后的dist目录结构如下图所示
dist目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值