vue项目跨域的问题前端解决方法(一个项目对接两个不同的域名、端口接口导致跨域,最好的办法是后端解决)
前端解决方法:
①打开config文件---->index.js文件,找到
proxyTable: {}
添加以下代码:
proxyTable: {'/api': {target: 'http://192.168.5.2:8089/',//设置你调用的接口域名和端口号 别忘了加httpchangeOrigin: true, //這裡true表示实现跨域pathRewrite: {'^/api':'/'//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://192.168.5.2:8089/comment/add',直接写‘/api/comment/add’就可以啦},},},
②打开main.js 将axios挂载到原型上
`import Axios from ‘axios’ //导入axios
//将axios挂载到原型上 Vue.prototype.$axios = Axios;`
③通过this.axios.来实现数据请求就可以啦this.axios.来实现数据请求就可以啦 this.axios.来实现数据请求就可以啦this.axios.get请求
this.$axios({methods:'GET',url:'api/...',//接口地址}).then(res=>{console.log('返回数据成功',res);this.$message({type: 'success',message:res.data.message});}).catch(res=>{console.log('返回数据失败',res);this.$message({type: 'warning',message:res.data.message});})
this.$axios.post请求
this.$axios.post('api/...',data).then(res=>{//data为请求参数对象console.log('返回数据成功111',res);// this.tableList=res.data.data;//this.dialogTableVisible=false;this.$message({type: 'success',message:res.data.message});}).catch(res=>{console.log('返回数据失败111',res);this.$message({type: 'warning',message:res.data.message});})
路过的小伙伴给个赞鸭~谢恩
转发请注明原创噢~~~~
vue项目跨域的问题(一个项目对接两个不同的域名 端口接口导致跨域 最好的办法是后端解决)
如果觉得《vue项目跨域的问题(一个项目对接两个不同的域名 端口接口导致跨域 最好的办法是后》对你有帮助,请点赞、收藏,并留下你的观点哦!