工具版本:
【vue -V】:2.9.6
ide工具:VSCode / Idea
前提:我们前端vue工程需要单独部署
一、本地使用命令运行跨域问题。
外网访问的地址:https://www.runoob.com/try/ajax/json_demo.json
本地springboot接口访问的地址:http://192.168.3.12:8081/register/getSmsCode/123456789
1、axios访问的代码:
created(){const _this = thisthis.$axios.get('/try/ajax/json_demo.json').then(response => (console.log('请求成功'),console.log(response),_this.msg = response.data)).catch(function (error) { // 请求失败处理console.log(error);});//发送本地springboot请求,本机的地址:192.168.3.12this.$axios.get('/register/getSmsCode/123456789').then(resp => (console.log('请求本地接口OK'),console.log(resp),_this.springStr = resp.data)).catch(function (error) { // 请求失败处理console.log("请求本地接口失败");});}
截图如下:
备注:需要在main.js中全局注册
importaxios from 'axios'
Vue.prototype.$axios = axios //全局注册,使用方法为:this.$axios
2、修改assetsPublicPath配置
配置 config—index.js中的build模块
将assetsPublicPath: ‘/’, 修改为 assetsPublicPath: ‘./’,
截图如下:
打包后的index.html路径为下面:
<script type=text/javascript src=./static/js/vendor.096d28cd4f5da166f9ce.js>
访问地址:http://localhost:8080/
点击button跳转页面后的地址:http://localhost:8080/#/test
备注:这个/test是从首页的button跳转过来的 【this.$router.push(’/test’)】
3、修改proxyTable配置
assetsSubDirectory: 'static',assetsPublicPath: '/',proxyTable: {'/try': {target:'https://www.runoob.com', // 你请求的第三方接口changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题},'/register': {target:'http://192.168.3.12:8081', // 本地的springboot接口changeOrigin:true, //}},
截图如下:
4、测试运行:
我们通过【npm run dev】启动我们的服务,通过【http://localhost:8080】就可以访问。
我们本机可以访问,但是在其它的主机上访问拒绝(使用nginx部署不会有这个问题)设置config---index.js中的host: 'localhost', // can be overwritten by process.env.HOST为:host: '0.0.0.0', // can be overwritten by process.env.HOST
备注,使用proxyTable只能解决本地跨域问题。如果部署到nginx就不会
二、部署到nginx配置。(在window环境中)
nginx版本:nginx version: nginx/1.19.0
启动nginx
直接在cmd中运行 nginx,不报错就启动了。
【tasklist|findstr “nginx”】可以查看是否启动过
结束服务【taskkill /f /im nginx.exe】
打包【npm run build】,生成dist文件夹,将dist里面的文件复制到nginx目录中【.../nginx/html/vue/】配置nginx.conf文件
server {listen 8888;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location /try { proxy_pass https://www.runoob.com; //internet api}location /register { proxy_pass http://192.168.3.12:8081; // local spring boot api}访问地址:【http://localhost:8888/vue/#/】vue就是nginx里面创建的目录
点击button,可以正常axios请求(外网和本地的springboot接口)
本地的nginx配置如下图:
运行结果如下图: