vue跨域

一、后台更改header

1:header('Access-Control-Allow-Origin:*');//允许所有来源访问 :
2:header('Access-Control-Allow-Method:POST,GET');//允许访问的方式  

二、使用JQuery提供的jsonp (注:vue中引入jquery)

methods: { 
 getData () { 
 var self = this
 $.ajax({ 
  url: 'http://f.apiplus.cn/bj11x5.json', 
  type: 'GET', 
  dataType: 'JSONP', 
  success: function (res) { 
  self.data = res.data.slice(0, 3) 
  self.opencode = res.data[0].opencode.split(',') 
  } 
 }) 
 } 
}

三、使用http-proxy-middleware 代理解决(项目使用vue-cli脚手架搭建)

例如请求的url:“http://f.apiplus.cn/bj11x5.json”
1、打开config/index.js,在proxyTable中添写如下代码:

proxyTable: { 
 '/api': { //使用"/api"来代替"http://f.apiplus.c" 
 target: 'http://f.apiplus.cn', //源地址 
 changeOrigin: true, //改变源 
 pathRewrite: { 
  '^/api': 'http://f.apiplus.cn' //路径重写 
  } 
 } 
}

2、使用axios请求数据时直接使用“/api”:

getData () { 
 axios.get('/api/bj11x5.json', function (res) { 
   console.log(res) 
 })

通过这中方法去解决跨域,打包部署时还按这种方法会出问题。解决方法如下:

let serverUrl = '/api/'  //本地调试时 
// let serverUrl = 'http://f.apiplus.cn/'  //打包部署上线时 
export default { 
  dataUrl: serverUrl + 'bj11x5.json' 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值