跨域

作者: 凛冬已至_123 | 来源:发表于2018-05-15 19:08 被阅读0次

同源策略(Same origin Policy)


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

本域指的是?

不同源的例子:

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

报错范例:

server,浏览器访问 http://localhost:8080/index.html
server.js

var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')

http.createServer(function(req, res){

  var pathObj = url.parse(req.url, true)

  switch (pathObj.pathname) {
    case '/getWeather':
      res.end(JSON.stringify({beijing: 'sunny'}))
      break;

    default:
      fs.readFile(path.join(__dirname, pathObj.pathname), function(e, data){
        if(e){
          res.writeHead(404, 'not found')
          res.end('<h1>404 Not Found</h1>')
        }else{
          res.end(data)
        }
      }) 
  }
}).listen(8080)

index.html

<h1>饥人谷</h1>
<script>
  var xhr = new XMLHttpRequest()
  xhr.open('GET','http://localhost:8080/getWeather', true)
  xhr.send()
  xhr.onload = function(){
    console.log(xhr.responseText)
  }
</script

跨域的几种方法


JSONP

HTML 中 script 标签可以加载其他域下的js,比如我们经常引入一个其他域下线上cdn的jQuery。那如何利用这个特性实现从其他域下获取数据呢?
可以先这样试试:

<script src="http://api.jirengu.com/weather.php"></script>

这时候会向天气接口发送请求获取数据,获取数据后做为 js 来执行。 但这里有个问题, 数据是 JSON 格式的数据,直接作为 JS 运行的话我如何去得到这个数据来操作呢?
这样试试:

<script src="http://api.jirengu.com/weather.php?callback=showData"></script>

这个请求到达后端后,后端会去解析callback这个参数获取到字符串showData,在发送数据做如下处理:
之前后端返回数据: {"city": "hangzhou", "weather": "晴天"} 现在后端返回数据: showData({"city": "hangzhou", "weather": "晴天"}) 前端script标签在加载数据后会把 「showData({“city”: “hangzhou”, “weather”: “晴天”})」做为 js 来执行,这实际上就是调用showData这个函数,同时参数是 {“city”: “hangzhou”, “weather”: “晴天”}。 用户只需要在加载提前在页面定义好showData这个全局函数,在函数内部处理参数即可。

<script>
function showData(ret){
console.log(ret);
}
</script>
<script src="http://api.jirengu.com/weather.php?callback=showData"></script>

这就是 JSONP(JSON with padding),总结一下:

JSONP是通过 script 标签加载数据的方式去获取数据当做 JS 代码来执行 提前在页面上声明一个函数,函数名通过接口传参的方式传给后台,后台解析到函数名后在原始数据上「包裹」这个函数名,发送给前端。换句话说,JSONP 需要对应接口的后端的配合才能实现。
server.js

var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')

http.createServer(function(req, res){
  var pathObj = url.parse(req.url, true)

  switch (pathObj.pathname) {
    case '/getNews':
      var news = [
        "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
        "正直播柴飚/洪炜出战 男双力争会师决赛",
        "女排将死磕巴西!郎平安排男陪练模仿对方核心"
        ]
      res.setHeader('Content-Type','text/json; charset=utf-8')
      if(pathObj.query.callback){
        res.end(pathObj.query.callback + '(' + JSON.stringify(news) + ')')
      }else{
        res.end(JSON.stringify(news))
      }

      break;

    default:
      fs.readFile(path.join(__dirname, pathObj.pathname), function(e, data){
        if(e){
          res.writeHead(404, 'not found')
          res.end('<h1>404 Not Found</h1>')
        }else{
          res.end(data)
        }
      }) 
  }
}).listen(8080)

index.html

<!DOCTYPE html>
<html>
<body>
  <div class="container">
    <ul class="news">
    </ul>
    <button class="show">show news</button>
  </div>

<script>

  $('.show').addEventListener('click', function(){
    var script = document.createElement('script');
    script.src = 'http://127.0.0.1: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);
    $('.news').innerHTML = html;
  }

  function $(id){
    return document.querySelector(id);
  }
</script>

</html>

打开终端,输入 node server.js ,浏览器打开 http://localhost:8080/index.html

CORS

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

var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')

http.createServer(function(req, res){
  var pathObj = url.parse(req.url, true)

  switch (pathObj.pathname) {
    case '/getNews':
      var news = [
        "第11日前瞻:中国冲击4金 博尔特再战200米羽球",
        "正直播柴飚/洪炜出战 男双力争会师决赛",
        "女排将死磕巴西!郎平安排男陪练模仿对方核心"
        ]

      res.setHeader('Access-Control-Allow-Origin','http://localhost:8080')
      //res.setHeader('Access-Control-Allow-Origin','*')
      res.end(JSON.stringify(news))
      break;
    default:
      fs.readFile(path.join(__dirname, pathObj.pathname), function(e, data){
        if(e){
          res.writeHead(404, 'not found')
          res.end('<h1>404 Not Found</h1>')
        }else{
          res.end(data)
        }
      }) 
  }
}).listen(8080)

index.html

<!DOCTYPE html>
<html>
<body>
  <div class="container">
    <ul class="news">

    </ul>
    <button class="show">show news</button>
  </div>

<script>

  $('.show').addEventListener('click', function(){
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://127.0.0.1:8080/getNews', true)
    xhr.send()
    xhr.onload = function(){
      appendHtml(JSON.parse(xhr.responseText))
    }
  })

  function appendHtml(news){
    var html = ''
    for( var i=0; i<news.length; i++){
      html += '<li>' + news[i] + '</li>'
    }
    $('.news').innerHTML = html
  }

  function $(selector){
    return document.querySelector(selector)
  }
</script>
</html>

启动终端,执行 node server.js ,浏览器打开 http://localhost:8080/index.html ,查看效果和网络请求

降域


a.baidu.com下的文件问index.html
b.baidu.com下的文件问index.html
在两个index.html下同时写入js代码document.domain="baidu.com"
这是域名都降为baidu.com
所以网页a.baidu.com(a.baidu.com:80/index.html)
和网页b.baidu.com(b.baidu.com:80/index.html)
之间就可以跨域数据交互了

代码如下:
a.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
<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>
</head>
<body>     
<!-- //样式从下面开始解读 -->
      <div class="ct">
        <h1>使用降域实现跨域</h1>
        <div class="main">
          <input type="text" placeholder="http://a.baidu.com:8080/a.html我是输入框默认显示">
        </div>
        
        <!-- //ifame标签可以在当前窗口建立一个子窗口;窗口显示b.baidu.com:8080/b.html这个域名的内容 -->
        <iframe src="http://b.baidu.com:8080/b.html" frameborder="0" ></iframe>
      </div>

      <script>
      //URL: http://a.baidu.com:8080/a.html
      //添加一个事件输入框内容变化出发(input事件)
      document.querySelector('.main input').addEventListener('input', function(){
        console.log(this.value);//在控制台打印输入框输入的内容
        //window.frames获取当前窗口中的所有子窗口得到一个类数组对象,其实就是针对选中<ifame>创建的子窗口
        //下面的代码是选中窗口后在通过document.querySelector('input')选中b.html中的输入框(input)然后把当前窗口输入的值(this.value)赋给b.html中的input
        //就是a.html中输入什么b.html中就显示什么
        window.frames[0].document.querySelector('input').value = this.value;
      })
      
      //降域
      //只有a.html和b.html中同时降域为baidu.com上面的input事件中的赋值操作才生效
      //也就是a.html通过跨域操作了b.html中的内容
      document.domain = "baidu.com"
      </script>
</body>
</html>

b.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
      html,body{
          margin: 0;
      }
      input{
          margin: 20px;
          width: 200px;
      }
  </style>
</head>
<body>
<input id="input" type="text"  placeholder="http://b.baidu.com:8080/b.html我是输入框默认显示">
<script>
// URL: http://b.baidu.com:8080/b.html

document.querySelector('#input').addEventListener('input', function(){
    //同a.html中相同这边这边输入框输入上面同样赋值给那边
    //window.parent选择当前前窗口的父窗口一般只有一个
    window.parent.document.querySelector('input').value = this.value;
})
//降域
document.domain = 'baidu.com';
</script>
</body>
</html>

postMessage

因为降域的局限性比较大,只能使用到有降域空间的域名上,那么当两个主域名完全不同时,应该如何处理呢?来看看新方法 postMessage。
postMessage 原理

  • postMessage 是 HTML5 中新增方法,可实现跨域通信;

  • postMessage 并不是向服务器读写资源,只是向外发送消息而已;可以把它当做使用手机发送短信消息,仅此而已。

  • 也就是:A 页面向 B 页面发送了一条消息,B 页面会接受到该消息,如果 B 页面需要该消息,则监听 message;否则无需关心该消息
    下面直接看代码
    a.com

var input = document.querySelector('.main input');
    input.addEventListener('input', function () {
       console.log('window:' + this.value);
     window.frames[0].postMessage(this.value, '*');
    });

    window.addEventListener('message', function (e) {
       console.log('window:'+ e.data);
    input.value = e.data;
 })

b.com

var input = document.querySelector('input');
    input.addEventListener('input', function () {
        console.log('iframe:'+ this.value);
        window.parent.postMessage(this.value, 'http://a.com:8080');
    });

    window.addEventListener('message', function (e) {
        console.log('ifream:'+ e.data);
        input.value = e.data;
    })

相关文章

网友评论

    本文标题:跨域

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