跨域

作者: hhg121 | 来源:发表于2017-07-14 23:25 被阅读14次

1: 什么是同源策略

同源策略(Same origin Policy),浏览器出于安全方面的考虑,只允许与本域下的接口交互。不同源的客户端脚本在没有明确授权的情况下,不能读写对方的资源。
本域指的是:

  • 同协议:如都是http或者https
  • 同域名:如都是http:// jirengu.com/a 和http:// jirengu.com/b
  • 同端口:如都是80端口
    例子:
http://jirengu.com/a/b.js 和 http://jirengu.com/index.php (同源)
不同源的例子:

http://jirengu.com/main.js 和 https://jirengu.com/a.php (协议不同)
http://jirengu.com/main.js 和 http://bbs.jirengu.com/a.php (域名不同,域名必须完全相同才可以)
http://jiengu.com/main.js 和 http://jirengu.com:8080/a.php (端口不同,第一个是80)

2: 什么是跨域?跨域有几种实现形式

跨域就是实现不同域之间的相互访问。

  1. JSONP
  2. CORS(用了ajax)
  3. 降域
  4. postMessage

下面将开始分别讲解四种方式:

JSONP

jsonp是json with padding(填充式json或参数式json)的简写。html中script标签可以引入其他域下的js,比如引入线上的jquery库。利用这个特性,可实现跨域访问接口,需要后端支持。其中src的链接会被当成js执行。

  1. 定义数据处理函数_fun
  2. 创建script标签,src的地址执行后端接口,最后加个参数callback=_fun
  3. 服务端在收到请求后,解析参数,计算返回数据,输出fun(data)字符串。
  4. fun(data)会放到script标签作为js执行。此时会调用fun函数,将data作为参数,所以我们无需再执行fun()函数,因为再script标签中会执行
<!-- 直接file中打开此文件,打开服务端,模仿跨域 -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>news</title>
  <style>
  .contain {
     width: 900px;
     margin: 0 auto;
  }
  </style>
</head>
<body>
  <div class="contain">
    <ul class="news">
      <li>第11日前瞻:中国冲击4金 博尔特再战</li>
      <li>男双力争会师决赛</li>
      <li>女排将死磕巴西!</li>
    </ul>
    <button class="change">换一组</button>
  </div>
  <script type="text/javascript">
    $('.change').addEventListener('click',function(){
        var script = document.createElement('script');
        script.src = 'http://localhost:8080/getNews?callback=appendHtml';
        document.head.appendChild(script);
        document.head.removeChild(script);
    })
    function appendHtml(news){
        var html = '';
        for (var i = news.length - 1; i >= 0; i--) {
            html += '<li>' + news[i] + '</li>';
        }
        $('.news').innerHTML = html;
    }
    function $(id){
        return document.querySelector(id);
    }
  </script>
</body>
</html>


app.get('/getNews', function(req, res){

    var news = [
        "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
        "正直播柴飚/洪炜出战 男双力争会师决赛",
        "女排将死磕巴西!郎平安排男陪练模仿对方核心",
        "没有中国选手和巨星的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;
    if(cb){
        res.send(cb + '('+ JSON.stringify(data) + ')');
    }else{
        res.send(data);
    }
    //appendHtml(['1xxx','2xxx'])
})

cors

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

<!-- 为了模仿跨域,我们将设置a.jrg.com和b.jrg.com他俩都指向127.0.0.1,这样我们
在 a.jrg.com:8080打开网页,向b.jrg.com发送请求。-->
<!--html和上面一样 -->
  <script type="text/javascript">
    $('.change').addEventListener('click',function(){
        var xhr = new XMLHttpRequest();
      xhr.open('get','http://b.jrg.com:8080/getNews',true);
      xhr.send();
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
          if(xhr.status === 200 || xhr.statue === 304){
            var result = JSON.parse(xhr.responseText);
            appendHtml(result);
          }
        }
      }
    })
    function appendHtml(news){               
        var html = '';
        for (var i = news.length - 1; i >= 0; i--) {
            html += '<li>' + news[i] + '</li>';
        }
        $('.news').innerHTML = html;
    }
    function $(id){
        return document.querySelector(id);
    }
  </script>
</body>
</html>
app.get('/getNews', function(req, res){
    var news = [
        "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
        "正直播柴飚/洪炜出战 男双力争会师决赛",
        "女排将死磕巴西!郎平安排男陪练模仿对方核心",
        "没有中国选手和巨星的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','http://a.jrg.com:8080');  
    //res.header('Access-Control-Allow-Origin','*');
    res.send(data);
})

降域

降域是相对于iframe元素而言的 。
一般来说域名为http:// b.jrg.com/b的网页以iframe的形式嵌在域名为http:// a.jrg.com/a的网页中,浏览器发现该请求不符合同源策略,正常情况下不能进行跨域访问,但是当我们在两个页面中分别设置documet.domain = jrg.com的时候(注意观察这个方法有一个限制就是 域名中必须有相同的部分),B页面就可以访问到A页面中的资源了,比如下面的代码:

<html>
<head>
  <meta charset="utf-8">
</head>
<style>
  .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>
<div class="ct">
  <h1>使用降域实现跨域</h1>
  <div class="main">
    <input type="text" placeholder="http://a.jrg.com:8080/a.html">
  </div>
  <iframe src="http://b.jrg.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 = "jrg.com";        //降域
</script>
</html>
<html>
<head>
  <meta charset="utf-8">
</head>
<style>
    html,body{
        margin: 0;
    }
    input{
        margin: 20px;
        width: 200px;
    }
</style>
    <input id="input" type="text"  placeholder="http://b.jrg.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
 document.querySelector('input').addEventListener('input',function(){
  console.log(this.value);
  window.parent.document.querySelector('.main input').value = this.value
})
document.domain = "jrg.com";       //降域
</script>
</html>

PostMessage

window.postMessage()是HTML5的新方法,可以使用它来向其它的window对象发送数据,无论这个window对象是属于同源或不同源,IE8+支持。
otherWindow.postMessage(message, targetOrigin);

  • otherWindow
    其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。
  • message
    要传递的数据。html5规范中提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以我们在传递参数的时候需要使用JSON.stringify()方法对对象参数序列化.
  • 通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串""(表示无限制)或者一个URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。这个机制用来控制消息可以发送到哪些窗口;例如,当用postMessage传送密码时,这个参数就显得尤为重要,必须保证它的值与这条包含密码的信息的预期接受者的orign属性完全一致,来防止密码被恶意的第三方截获。如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个有确切值的targetOrigin,而不是。不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。
//html同上
//a.html
<script>
//URL: http://a.jrg.com:8080/a.html
  $('.main input').addEventListener('input',function(){
    console.log(this.value);
    window.frames[0].postmessage(this.value,'*');
  });
  window.addEventListener('message',function(e){
    $('.main input') = e.data;
    console.log(e.data);
  });
  function $(id){
    return document.querySelector(id);
  }
</script>
<script>

// URL: http://b.jrg.com:8080/b.html
  $('input').addEventListener('input',function(){
    console.log(this.value);
    window.parent.postmessage(this.value,'*');
  });
  window.addEventListener('message',function(e){
    $('input') = e.data;
    console.log(e.data);
  });
  function $(id){
    return document.querySelector(id);
  }
</script>

相关文章

网友评论

      本文标题:跨域

      本文链接:https://www.haomeiwen.com/subject/piynhxtx.html