跨域

2017-08-09  本文已影响0人  谨言_慎行

1. 什么是同源策略

浏览器出于安全方面的考虑,只允许与本域下的接口交互。不同源的客户端脚本在没有明确授权的情况下,不能读写对方的资源。
本域指的是?
同协议:如都是http或者https
同域名:如都是http://jirengu.com/ahttp://jirengu.com/b
同端口:如都是80端口

如:
http://jirengu.com/a/b.jshttp://jirengu.com/index.php (同源)

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

**需要注意的是: 对于当前页面来说页面存放的 JS 文件的域不重要,重要的是加载该 JS 页面所在什么域 **

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

3. JSONP 的原理是什么

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>news</title>
<style>
  .container{
    width: 900px;
    margin: 0 auto;
  }
</style>
</head>
<body>
  <div class="container">
    <ul class="news">
      <li>第11日前瞻:中国冲击4金 博尔特再战</li>
      <li>男双力争会师决赛 </li> 
      <li>女排将死磕巴西!</li>
    </ul>
    <button class="change">换一组</button>
  </div> 
<script>
  $('.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=0; i<news.length; 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) + ')');   // 3
    }else{
        res.send(data);      
    }
})
  1. 定义数据处理函数_fun
  2. 创建script标签,src的地址执行后端接口,最后加个参数callback=_fun
  3. 服务端在收到请求后,解析参数,计算返还数据,输出 fun(data) 字符串。
  4. fun(data)会放到script标签做为js执行。此时会调用fun函数,将data做为参数

4.CORS是什么

(1) 请求方法是以下三种方法之一:
HEAD
GET
POST
(2)HTTP的头信息不超出以下几种字段:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain

对于简单请求,浏览器直接发出CORS请求就是在头信息之中,增加一个Origin字段,服务器根据这个值,决定是否同意这次请求。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>news</title>
<style>
  .container{
    width: 900px;
    margin: 0 auto;
  }
</style>
</head>
<body>
  <div class="container">
    <ul class="news">
      <li>第11日前瞻:中国冲击4金 博尔特再战</li>
      <li>男双力争会师决赛 </li> 
      <li>女排将死磕巴西!</li>
    </ul>
    <button class="change">换一组</button>
  </div>
  
<script>
  
  $('.change').addEventListener('click', function(){
    var xhr = new XMLHttpRequest();
    xhr.open('get', 'http://localhost:8080/getNews', true);
    xhr.send();
    xhr.onreadystatechange = function(){
      if(xhr.readyState === 4 && xhr.status === 200){
        appendHtml( JSON.parse(xhr.responseText) )
      }
    }
    window.xhr = xhr
  })
  function appendHtml(news){
    var html = '';
    for( var i=0; i<news.length; i++){
      html += '<li>' + news[i] + '</li>';
    }
    console.log(html);
    $('.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", "*");          // Origin
    res.send(data);
})
image.png

5.降域

在一个网页中用iframe标签引入另一个网站时,该网页是你自己的一个网页,一级域名相同,只是二级域名不同,这种情况下,可以通过降域的方式实现两个窗口之间的通信。通过设置网页的 domain 属性实现

<html>
<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>
<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(){
    window.parent.document.querySelector('input').value = this.value;
})
document.domain = 'jrg.com';     // 降域
</script>
</html>

6.postmessage

跨文档通信 API(Cross-document messaging)为window对象新增了一个window.postMessage方法,允许跨窗口通信,不论这两个窗口是否同源。

<html>
<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>使用postMessage实现跨域</h1>
    <div class="main">
        <input type="text" placeholder="http://a.jrg.com:8080/a.html">
    </div>

    <iframe src="http://localhost:8080/b.html" frameborder="0" ></iframe>

</div>


<script>
//URL: http://a.jrg.com:8080/a.html
$('.main input').addEventListener('input', function(){
    console.log(this.value);
    window.frames[0].postMessage(this.value,'*');     // postMessage
})
window.addEventListener('message',function(e) {
        $('.main input').value = e.data
    console.log(e.data);
});
function $(id){
    return document.querySelector(id);
}
</script>
</html>
<html>
<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
 
$('#input').addEventListener('input', function(){
    window.parent.postMessage(this.value, '*');             // postMessage
})
window.addEventListener('message',function(e) {
        $('#input').value = e.data
    console.log(e.data);
});
function $(id){
    return document.querySelector(id);
}   
</script>
</html>
上一篇 下一篇

猜你喜欢

热点阅读