美文网首页
关于跨域

关于跨域

作者: gzy_a5a4 | 来源:发表于2018-09-23 01:25 被阅读0次

    同源策略

    同源策略限制了一个源(origin)中加载的文档或脚本与其他源(origin)中的资源交互的方式。这是一种用来隔离潜在恶意文档的关键安全机制。

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

    同协议:如都是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)


    跨域

    跨域即越过同源策略,允许浏览器执行其他网站的脚本。

    实现形式有:

    1.JSONP

    2.CORS

    3.降域

    4.postMessage


    JSONP

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

    将接口放在<script>的 src 中,浏览器向这个地址获取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) + ')')      //callback
          }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){                //appendHtml()函数
        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>
    

    CORS

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


    降域

    有2个html文件,使用<iframe>相关联,要使其可以实现跨域,都加上document.domin = "降到共同的主域"

    <input type="text" placeholder="http://a.jrg.com:8080/a.html">
    
    <iframe src="http://b.jrg.com:8080/b.html" frameborder="0"></iframe>
    
    //URL: http://a.jrg.com:8080/a.html
    
    doucument.domain = "jrg.com"
    

    postMessage

    <input type="text" placeholder="http://a.jrg.com:8080/a.html">
    
    <iframe src="http://b.jrg.com:8080/b.html" frameborder="0"></iframe>
    
    //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').value = e.data
        console.log(e.data)
    })
    
    <input id="input" type="text" placeholder="http://b.jrg.com:8080/b.html">
    
    //URL: http://b.jrg.com:8080/b.html
    
    $('#input').addEventListener('input',function(){
        window.parent.postMessage(this.value, '*')
    })
    
    window.addEventListener('message', function(e){                //监听 message 事件
        $('#input').value = e.data
        console.log(e.data)
    })
    

    参考:饥人谷

    相关文章

      网友评论

          本文标题:关于跨域

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