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目录结构如下图所示