vue项目跨域的问题(一个项目对接两个不同的域名、端口接口导致跨域,最好的办法是后端解决)

vue项目跨域的问题前端解决方法(一个项目对接两个不同的域名、端口接口导致跨域,最好的办法是后端解决)

前端解决方法:

①打开config文件---->index.js文件,找到

proxyTable: {}

添加以下代码:

  proxyTable: {
        '/api': {
               target: 'http://192.168.5.2:8089/',//设置你调用的接口域名和端口号 别忘了加http
               changeOrigin: 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. a x i o s . 来 实 现 数 据 请 求 就 可 以 啦 t h i s . 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
                });
              })

路过的小伙伴给个赞鸭~谢恩
转发请注明原创噢~~~~

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值