vue本地请求接口时以代理的方式解决跨域

1.首先找到这个文件,可能脚手架版本不一样,但是这个文件是一定有的
在这里插入图片描述
2.然后在这个叫做dev的对象里面插入proxyTable这个属性
在这里插入图片描述
例:

 proxyTable: {
      '/api': {
        target: 'http://xxx.xxxx.xx/', //设置调用的接口域名和端口号
        changeOrigin: true,//如果需要跨域
        ws:true,
        pathRewrite:{
          '^/api':''
       }
      }
    }

3.这样你就可以在main.js文件配置默认url前缀的时候进行添加了

例:

// // 设置axios默认url前缀
if (location.href.indexOf('http://localhost:8080') !== -1) { // 本地时
  axios.defaults.baseURL = '/api'
} else if (location.href.indexOf('https') !== -1) {  // https协议时
  axios.defaults.baseURL = 'https://xxx.xxx.xx'
} else { // http协议时
  axios.defaults.baseURL = 'http://xxx.xxx.xx'
}

4.然后你在本地开发时用axios请求这个(http://xxx/xxx/xx)的接口是就不会跨域了

例:

       this.$axios({
          url: '/aa/aa',
          method: 'post'
        }).then(res => {
           console.log(res)
        }

就相当于访问http://localhost:8080/api/aa/aa ==> http://xxx/xxx/xx/aa/aa这个接口了

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值