最近在阿里云上买了一个域名和两个服务器,一个服务器内地的还在审核,另一个是香港服务器,想把之前做的一些小demo放上面运行看看,顺便了解线上跨域问题。
前端跨域问题可以从两个方面入手:
1. 开发环境时的跨域解决
1 2 3 4 5
| VUE_APP_FLAG = "/devApi"
VUE_APP_APIURL = 'http://www.web-jshtml.cn/productapi/token'
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import axios from "axios";
let baseUrl = process.env.VUE_APP_FLAG;
const service = axios.create({ baseURL: baseUrl, timeout: 5000, });
service.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error); });
service.interceptors.response.use(function (response) { let data = response.data;
if (data.resCode !== 0) { ElMessage({ showClose: true, message: data.message, type: "error", }); return Promise.reject(error); } else { return response }
}, function (error) { return Promise.reject(error); });
export function GetSms(data) { return service.request({ url: '/getSms/', method: 'post', data }) }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| setTimeout(() => { GetSms(data) .then((res) => { console.log(route); console.log(res); ElMessage({ showClose: true, message: res.data.message, type: "success", });
countDown(60); }) .catch((error) => { console.log(error); }); }, 1500);
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| devServer: { open: false, host: '0.0.0.0', port: 8080, https: false, hot: true, hotOnly: false, proxy: { [process.env.VUE_APP_FLAG]: { target: process.env.VUE_APP_APIURL, changeOrigin: true, ws: false, pathRewrite: { [`^${process.env.VUE_APP_FLAG}`]: ''
} }, }
|
- 当前端项目打包上线后,vue.config.js的配置不能起作用了,需要在线上服务器进行配置
2. 生产环境时的跨域问题
-
服务器安装nginx服务器(为了方便使用宝塔Linux面板安装,宝塔软件安装目录在/www/server/下)
-
nginx的配置 把dist中的内容放到nginx安装目录下的html文件夹里
-
也可以在conf文件夹的nginx.conf中修改要映射的文件夹
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| http { server { listen 80; server_name localhost;
location / { root /www/server/nginx/html; index index.html index.htm index.php; } location /devApi/ { proxy_pass http: }
} server { listen 80; server_name wyz.baicaitang.top; location / { root /www/server/nginx/html; index index.html index.htm index.php; } location /devApi/ { proxy_pass http: }
access_log /www/wwwlogs/access.log; } }
|
- 更改完需重载nginx:
nginx -s reload