vue跨域解决方法

一、什么是跨域

跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。

所谓同源是指,域名,协议,端口均相同,举个例子:

http://www.123.com/index.html 调用 http://www.123.com/server.php (非跨域)

http://www.123.com/index.html 调用 http://www.456.com/server.php (主域名不同:123/456,跨域)

http://abc.123.com/index.html 调用 http://def.123.com/server.php (子域名不同:abc/def,跨域)

http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)

http://www.123.com/index.html 调用 https://www.123.com/server.php (协议不同:http/https,跨域)

请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。

二、解决方法

1、后台改header

     header('Access-Control-Allow-Origin:*');//允许所有来源访问 

  header('Access-Control-Allow-Method:POST,GET');//允许访问的方式   

2、使用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(',') 

      

    }) 

  

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

例如请求的url:“http://f.apiplus.cn/bj11x5.json”

1)打开config/index.js,在proxyTable中添写如下代码:

     

1

2

3

4

5

6

7

8

9

proxyTable: { 

  '/api': {  //使用"/api"来代替"http://f.apiplus.c" 

    target: 'http://f.apiplus.cn', //源地址 

    changeOrigin: true, //改变源 

    pathRewrite: { 

      '^/api': 'http://f.apiplus.cn' //路径重写 

      

  

}

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

1

2

3

4

getData () { 

 axios.get('/api/bj11x5.json', function (res) { 

   console.log(res) 

 })

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

1

2

3

4

5

let serverUrl = '/api/'  //本地调试时 

// let serverUrl = 'http://f.apiplus.cn/'  //打包部署上线时 

export default { 

  dataUrl: serverUrl + 'bj11x5.json' 

}

调试时定义一个serverUrl来替换我们的“/api”,最后打包时,只需要将“http://www.xxx.com”替换这个“/api”就可以了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值