进阶13 跨域

2017-07-29  本文已影响0人  cheneyzhangch

题目1: 什么是同源策略

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

本域(同源)指的是

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

当前JS所在的页面的url和请求的地址的url不是同源,即跨域,请求会被浏览器阻止

实现形式

题目3: JSONP 的原理是什么

html中script标签可以引入其他域下的js,比如引入线上的jquery库。利用这个特性,可实现跨域访问接口。需要后端支持

  1. 定义数据处理函数_fun
  2. 创建script标签,script.src的地址: 后端接口,且最后加个参数callback=_fun //方便后端获取callback属性以确定返回值
  3. 服务端在收到请求后,解析参数,计算返还数据,输出 fun(data) 字符串。
  4. fun(data)会放到script标签做为js执行。此时会调用fun函数,将data做为参数。

缺点:

题目4: CORS是什么

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

题目5: 根据视频里的讲解演示三种以上跨域的解决方式 ,写成博客

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://127.0.0.1/getNews?callback=appendHtml';
    document.head.appendChild(script);  // 创建src标签,script.src的地址: 后端接口,且最后加个参数callback=数据处理函数
    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);
    $('.news').innerHTML = html;
  }
  function $(id){
    return document.querySelector(id);
  }
</script>



</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) + ')');  // 服务端在收到请求后,解析参数,计算返还数据,返回 fun(data) 字符串。
    }else{
        res.send(data);
    }
})

CORS

CORS实现跨域与普通的ajax在前端代码中并没有区别,重点在于后台返回数据时增加res.header

前台代码

<!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://b.jrg.com: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>



</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");  // 增加发起跨域请求的URL的响应头
    //res.header("Access-Control-Allow-Origin", "*");           //  *表示接受所有URL发起的跨域请求并作出相应
    res.send(data);
})

降域

当这两个域名都属于同一个基础域名(主域名一致,二级域名不一致),而且所用的协议类型、端口都一致的时候,可以使用降域来实现跨域, 可以通过将document.domain改成一样的来实现。
主要用于操作页面内iframe

<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>
上一篇 下一篇

猜你喜欢

热点阅读