前端常用的实现跨域的方法

这里说的js跨域是指通过js在不同的域之间进行数据传输或通信,比如用ajax向一个不同的域请求数据,或者通过js获取页面中不同域的框架中(iframe)的数据。只要协议、域名、端口有任何一个不同,都被当作是不同的域。
要解决跨域的问题,我们可以使用以下几种方法:

一、通过jsonp跨域

在js中,我们直接用XMLHttpRequest请求不同域上的数据时,是不可以的。但是,在页面上引入不同域上的js脚本文件却是可以的,jsonp正是利用这个特性来实现的。
例如:

//html代码:
<ul id="ct" class="news">
    <li>第11日前瞻:中国冲击4金</li>
    <li>男双力争会师决赛</li>
    <li>女排死磕巴西队</li>
  </ul>
  <a id="change" class="btn" href="#" >换一组</a>
  <script>
    document.querySelector('#change').addEventListener('click',function(){
      var script = document.createElement('script');
      script.src = 'http://b.zhuwei.com:8080/getNews?callback=appendHtml';
      document.head.appendChild(script);
      //document.head.removeChild(script);
    })
    function appendHtml(news){
      var html ='';
      for(var i=0;i<news.length;i++){
        html+='<li>'+news[i]+'</li>';
      }
      console.log(html);
      document.querySelector('#ct').innerHTML = html;
    }
  </script>



//router代码:
 app.get('/getNews',function(req,res){
    var news = [
      "第11日前瞻:中国冲击4金 博尔特再战200米",
      "正直播男双力争会师决赛",
      "女排将死磕巴西队",
      "没有中国选手和110巨星的110米跨栏",
      "中英上演奥运金牌大战",
      "博彩赔率挺中国夺回第二",
      "最“出柜”奥运?同性之爱闪耀里约",
      "下跪拜谢与洪荒之力一样 都是真情流露"
    ]
    var data = [];
    for(var i=0;i<3;i++){
      var index = parseInt(Math.random()*news.length);
      data.push(news[index]);
      news.splice(index,1);
    }
    var cb = req.query.callback;
    res.send(cb+'('+JSON.stringify(data)+')');
  })

在这个例子中,当点击按钮时,动态的创建了一个<script></script>标签,然后指定该标签的srchttp://zhuwei.com:8080/getNews,之后对该地址的内容作为参数执行appendHtml函数。从而实现了点击按钮,随机切换三条新闻展示在页面中的功能。

二、CORS跨域

CORS全城是跨域资源共享,(Cross-Origin Resource Sharing),是一种ajax跨域请求资源的方式,支持现代浏览器,支持IE10及以上。实现方法:当使用XMLHttpRequest发送请求时,浏览器发现该请求不符合同源策略,会给该请求加入一个响应头:Origin,后台进行一系列处理,如果确定接受请求则在返回结果中加入一个响应头:Access-Control-Allow-Origin;浏览器判断该相应头中是否包含Origin的值,如果有则浏览器会有处理响应,我们就可以拿到响应的数据,如果不包含,浏览器就直接驳回,这时我们无法拿到响应数据。

//html代码:
<ul id="ct" class="news">
    <li>第11日前瞻:中国冲击4金</li>
    <li>男双力争会师决赛</li>
    <li>女排死磕巴西队</li>
  </ul>
  <a id="change" class="btn" href="#" >换一组</a>
  <script>
    document.querySelector('#change').addEventListener('click',function(){
      var xhr = new XMLHttpRequest();
      xhr.open('get','http://b.zhuwei.com:8080/getNews',true);
      xhr.send();
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200){
          appendHtml(JSON.parse(xhr.responseText))
        }
      }
      })
    function appendHtml(news){
      var html ='';
      for(var i=0;i<news.length;i++){
        html+='<li>'+news[i]+'</li>';
      }
      console.log(html);
      document.querySelector('#ct').innerHTML = html;
    }

  </script>


//router代码:
  app.get('/getNews',function(req,res){

    var news = [
      "第11日前瞻:中国冲击4金 博尔特再战200米",
      "正直播男双力争会师决赛",
      "女排将死磕巴西队",
      "没有中国选手和110巨星的110米跨栏",
      "中英上演奥运金牌大战",
      "博彩赔率挺中国夺回第二",
      "最“出柜”奥运?同性之爱闪耀里约",
      "下跪拜谢与洪荒之力一样 都是真情流露"
    ]
    var data = [];
    for(var i=0;i<3;i++){
      var index = parseInt(Math.random()*news.length);
      data.push(news[index]);
      news.splice(index,1);
    }
   
    res.header("Access-Control-Allow-Origin","*");
    res.send(data);
  })

三、使用降域实现跨域

原理:相同主域名不同子域名下的页面,可以设置 document.domain 让它们同域
限制:
1.有其他页面 window 对象的引用。
2.二级域名相同。
3.协议相同。
4.端口相同。
使用方法就是将符合上述条件页面的 document.domain 设置为同样的二级域名。这样我们就可以使用其他页面的 window 对象引用。

//a.zhuwei.com:8080/a.html代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
  .ct{
    width: 910px;
    margin: auto;
  }
  .main{
    float: left;
    width: 450px;
    height: 300px;
    border: 1px solid #ccc;
  }
  .main input{
    margin: 20px;
    width: 200px;
  }
  .iframe{
    float: right;
  }
  iframe{
    width: 450px;
    height: 300px;
    border: 1px dashed #ccc;
  }

</style>
</head>
<body>
  <div class="ct">
    <h1>降域实现跨域</h1>
    <div class="main">
      <input type="text" placeholder="http://a.zhuwei.com:8080/a.html"></input>
    </div>
    <iframe src="http://b.zhuwei.com:8080/b.html" frameborder="0"></iframe>
  </div>
  <script>
    //URL: http://a.jrg.com:8080/a.html
  document.querySelector('.main input').addEventListener('input', function(){
  console.log(this.value);
  window.frames[0].document.querySelector('input').value = this.value;
})
document.domain = "zhuwei.com"
  </script>
  
</body>
</html>


//b.zhuwei.com:8080/b.html代码:
 <html>
<style>
  html,body{
    margin: 0;
  }
  input{
    margin: 20px;
    width: 200px;
  }
</style>

  <input id="input" type="text"  placeholder="http://b.zhuwei.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
 
document.querySelector('#input').addEventListener('input', function(){
  window.parent.document.querySelector('input').value = this.value;
})
document.domain = 'zhuwei.com';
</script>
</html>

通过降域 完成了跨域使a.zhuwei.com:8080/a.html可以操作不同域名下的b.zhuwei.com:8080/b.html

四、postMessage实现跨域

postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。

//a.zhuwei.com:8080/a.html代码:
<body>
  <div class="ct">
    <h1>postmessage实现跨域</h1>
    <div class="main">
      <input type="text" placeholder="http://a.zhuwei.com:8080/a.html"></input>
    </div>
    <iframe src="http://b.zhuwei.com:8080/b.html" frameborder="0"></iframe>
  </div>
  <script>
    //URL: http://a.jrg.com:8080/a.html
  document.querySelector('.main input').addEventListener('input', function(){
  
  window.frames[0].postMessage(this.value,'*');
  console.log(this.value);
})
window.addEventListener('message',function(e){
  document.querySelector('.main input').value = e.data
  console.log(e.data)
})
  </script>
  
</body>
</html>


//b.zhuwei.com:8080/b.html代码:
   <input id="input" type="text"  placeholder="http://b.zhuwei.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
 
document.querySelector('#input').addEventListener('input', function(){
  window.parent.postMessage(this.value,'*');
})
window.addEventListener('message',function(e){
  document.querySelector('#input').value = e.data
  console.log(e.data)
})
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 什么是跨域? 2.) 资源嵌入:、、、等dom标签,还有样式中background:url()、@font-fac...
    电影里的梦i阅读 6,927评论 0 5
  • 什么是同源策略? 同源策略是指,浏览器出于安全方面的考虑,只允许与本域下的接口交互。不同源的客户端脚本在没有明确授...
    upup_dayday阅读 1,787评论 0 0
  • 一、浏览器的同源策略 1.什么是同源? 所谓“同源”指的是”三个相同“。相同的域名、端口和协议,这三个相同的话就视...
    徐国军_plus阅读 4,302评论 1 3
  • 当想起为某人写东西的时候,不要犹豫-可能就这一次。 当想和某人真情流露的时候不要不好意思,因为时间过往-不复返。 ...
    在路上走着看天空阅读 1,638评论 0 0
  • 作者:澹台好好 江南,有着云烟一般的名字,粉壁黛瓦,绣帘雕窗,石栈小桥,杨柳堆烟。初到江南,就深深被她的婉约打动....
    SOMCENT阅读 4,127评论 0 0