进阶任务十三-跨域

  • 什么是同源策略
    同源策略限制从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的关键的安全机制。
    同源意味着协议相同、域名相同、端口相同。
    不同源的话,有三种行为受到限制:1、Cookie、LocalStorage 和 IndexDB 无法读取。 2、DOM 无法获得。3、AJAX 请求不能发送。

  • 什么是跨域?跨域有几种实现形式
    跨域是指从一个域名的网页去请求另一个域名的资源。跨域可以通过JSONP、CORS、降域、PostMessage等方式来实现

  • JSONP 的原理是什么
    HTML的<script>标签是同源策略的例外,可以突破同源策略从其他来源获取数据,因此可以通过<script>标签引入jsonp文件,然后通过一系列JS操作获取数据

  • CORS是什么
    CORS(Cross-Origin Resource Sharing)跨域资源共享,定义了必须在访问跨域资源时,浏览器与服务器应该如何沟通。CORS背后的基本思想就是使用自定义的HTTP头部让浏览器与服务器进行沟通,从而决定请求或响应是应该成功还是失败。服务器端对于CORS的支持,主要就是通过设置Access-Control-Allow-Origin来进行的。如果浏览器检测到相应的设置,就可以允许Ajax进行跨域的访问。

  • JSONP实现

前端代码:

<!doctype html>
<html>
<head>
    <style>
        .container {
            width: 900px;
            maring: 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: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>

后端代码:

//假设域名是localhost, 端口是8080

//更多详细使用方法参考 http://www.expressjs.com.cn/guide/routing.html

/**
 * 当 http://localhost:8080/getInfo 的GET请求到来时被下面匹配到进行处理
 * 发送JSON格式的响应数据 {name: 'ruoyu'}
 */
app.get("/getNews", function(req,res){
  var news = [
    "第11日前瞻:中国冲击4金,博尔特再战",
    "正直播出战,男双力争会师决赛",
    "女排将死磕巴西!郎平安排男陪练模仿对方核心",
    "没有中国选手和巨星的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)
  }
})
  • CORS实现

前端代码:

<!doctype html>
<html>
<head>
    <style>
        .container {
            width: 900px;
            maring: 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.onreadystatechange = function(){
            if(xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)){
              appendHTML(JSON.parse(xhr.responseText))
            }
          }
          xhr.open("get", "http://b.jrg.com:8080/getNews", true)
          xhr.send()
        })

        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金,博尔特再战",
    "正直播出战,男双力争会师决赛",
    "女排将死磕巴西!郎平安排男陪练模仿对方核心",
    "没有中国选手和巨星的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.send(JSON.stringify(data))
})
  • 降域实现:

前端a.html代码:

<!doctype html>
<html>
<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;
            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.jrg.com:8080/a.html">
        </div>
        <iframe src="http://b.jrg.com:8080/b.html" frameborder="0"></iframe>
    </div>
    <script>
        document.querySelector(".main input").addEventListener("input", function(){
            window.frames[0].document.querySelector("#input").value = this.value
        })
        document.domain = "jrg.com"
    </script>
</body>
</html>

前端b.html代码:

<!doctype html>
<html>
<head>
    <style>
        html,body {
            margin: 0;
        }

        input {
            margin: 20px;
            width: 200px;
        }
    </style>
</head>
<body>
    <input type="text" id="input" placeholder="http://b.jrg.com:8080/b.html">
    <script>
        document.querySelector("#input").addEventListener("input", function(){
            window.parent.document.querySelector("input").value = this.value;
        })
        document.domain = "jrg.com"
    </script>
</body>
</html>
  • PostMessage实现:

前端a.html代码:

<!doctype html>
<html>
<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;
            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.jrg.com:8080/a.html">
        </div>
        <iframe src="http://b.jrg.com:8080/b.html" frameborder="0"></iframe>
    </div>
    <script>
        document.querySelector(".main input").addEventListener("input", function(){
            window.frames[0].postMessage(this.value, "http://b.jrg.com:8080")
        })

        window.addEventListener("message", function(e){
             document.querySelector(".main input").value = e.data
        })
    </script>
</body>
</html>

前端b.html代码:

<!doctype html>
<html>
<head>
    <style>
        html,body {
            margin: 0;
        }

        input {
            margin: 20px;
            width: 200px;
        }
    </style>
</head>
<body>
    <input type="text" id="input" placeholder="http://b.jrg.com:8080/b.html">
    <script>
        document.querySelector("#input").addEventListener("input", function(){
            window.parent.postMessage(this.value, "http://a.jrg.com:8080")
        })
        window.addEventListener("message", function(e){
            document.querySelector("#input").value = e.data
        })
    </script>
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容

  • 前言 关于前端跨域的解决方法的多种多样实在让人目不暇接。以前碰到一个公司面试的场景是这样的,好几个人一起在等待面试...
    andreaxiang阅读 473评论 1 4
  • 什么是跨域? 2.) 资源嵌入:、、、等dom标签,还有样式中background:url()、@font-fac...
    电影里的梦i阅读 2,350评论 0 5
  • 前言 原文地址:前端跨域总结博主博客地址:Damonare的个人博客 正文 1. 什么是跨域? 跨域一词从字面意思...
    yo_yo_阅读 496评论 0 5
  • 章柒 十五:闻仲 “你是贵族?那为什么来碧游宫修道?人间不好玩吗?”师姐颜笙的问题接连不断,闻仲把肩上的水桶放在路...
    林喜喜阅读 310评论 0 0
  • 细茉阅读 278评论 0 0