我的前端學(xué)習(xí)筆記26——跨域

1评架,什么是同源策略

同源策略:
瀏覽器處于安全方面的考慮,只允許與本域下的接口交互炕泳,不同源的客戶(hù)端腳本在沒(méi)有明確授權(quán)的情況下纵诞,不能讀取對(duì)方的資源。

  • 同協(xié)議:(http培遵、file浙芙、shh、https籽腕、tel嗡呼、ftp...)以上協(xié)議必須相同;
  • 同域名:第一個(gè) // 到第二個(gè) / 之間的部分必須相同皇耗;
  • 同端口:一般為80南窗,具體看設(shè)置。

以上三條都相同則為同源廊宪。

2矾瘾,什么是跨域?跨域有幾種實(shí)現(xiàn)形式

  • 跨域:
    在使用ajax向后臺(tái)請(qǐng)求數(shù)據(jù)時(shí)箭启,如果接口域名不相同壕翩,即為跨域。
    換句話(huà)說(shuō)傅寡,允許不同域的接口進(jìn)行交互即為跨域放妈。

  • 跨域?qū)崿F(xiàn)形式:

  • JSONP

  • CORS

  • 降域

  • postMessage

3,JSONP 的原理是什么

應(yīng)用中我們發(fā)現(xiàn)荐操,使用<script>標(biāo)簽引用鏈接不會(huì)出現(xiàn)跨域問(wèn)題芜抒,因此,可以采用這種方式跨域托启。<script src='鏈接 '></script>宅倒。服務(wù)端不再返回JSON格式的數(shù)據(jù),而是返回一段調(diào)用某個(gè)函數(shù)的js代碼屯耸,在src中進(jìn)行了調(diào)用拐迁,這樣實(shí)現(xiàn)了跨域。

4疗绣,CORS是什么

  • CORS:跨域資源共享(Cross-origin resource sharing)
    它允許瀏覽器向跨源服務(wù)器线召,發(fā)出XMLHttpRequest請(qǐng)求,從而克服了AJAX只能同源使用的限制多矮。
  • 實(shí)現(xiàn)方式:
    當(dāng)你使用XMLHttpRequest發(fā)送請(qǐng)求時(shí)缓淹,瀏覽器發(fā)現(xiàn)該請(qǐng)求不符合同源策略,會(huì)給該請(qǐng)求加一個(gè)請(qǐng)求頭:Origin,后臺(tái)進(jìn)行一系列處理讯壶,如果確定接受請(qǐng)求則在返回結(jié)果中加入一個(gè)響應(yīng)頭:Access-Control-Allow-Origin; 瀏覽器判斷該相應(yīng)頭中是否包含Origin的值料仗,如果有則瀏覽器會(huì)處理響應(yīng),我們就可以拿到響應(yīng)數(shù)據(jù)鹏溯,如果不包含瀏覽器直接駁回罢维,這時(shí)我們無(wú)法拿到響應(yīng)數(shù)據(jù)淹仑。

轉(zhuǎn)載自:阮一峰博客

5丙挽,根據(jù)視頻里的講解演示三種以上跨域的解決方式

  • 方法一:JSONP
  • 優(yōu)勢(shì):
  • 不需要AJAX,只需要通過(guò)script標(biāo)簽即可完成向后臺(tái)發(fā)送請(qǐng)求并獲取數(shù)據(jù)匀借;
  • 劣勢(shì):
  • 需要后臺(tái)支持輸出指定格式的內(nèi)容颜阐,比如下面例子中的函數(shù)名需要后臺(tái)進(jìn)行配合;

html端:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>新聞加載example</title>
    <style media="screen">
      .newsFrame{
        margin: 0 auto;
      }
    </style>
  </head>
  <body>
    <div class="newsFrame">
      <ul class="content">
        <li>在北大聽(tīng)講座</li>
        <li>統(tǒng)計(jì)陷阱</li>
        <li>淺薄</li>
      </ul>
      <button class="btn">換一批</button>
    </div>


     <script type="text/javascript">
        $('.btn').addEventListener('click',function(){
          var script = document.createElement('script');
          script.src='http://b.har.com:8080/getNews?callback=appendhtml';

    //當(dāng)點(diǎn)擊按鈕時(shí)吓肋,會(huì)在head中生成一個(gè)script標(biāo)簽凳怨,并下載標(biāo)簽中引用的鏈接內(nèi)容。
    //返回的是appendhtml(內(nèi)容)是鬼,這個(gè)會(huì)被函數(shù)appendhtml執(zhí)行肤舞,放在html上。

          document.head.appendChild(script);
          document.head.removeChild(script);
        })
    //為了避免生成太多script標(biāo)簽均蜜,生成之后立刻刪除李剖,但是內(nèi)容已經(jīng)下載,不會(huì)影響囤耳。

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

      function $(id){
        return document.querySelector(id)
      }

    </script>
  </body>
</html>

后臺(tái)端:

app.get('/getNews', function(req, res) {

        var news = [
        "身邊的邏輯學(xué)",
        '牛奶可樂(lè)經(jīng)濟(jì)學(xué)',
        '看見(jiàn)',
        '論中國(guó)',
        '烏合之眾',
        '哲學(xué)的慰藉'
      ]
      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;
      res.send( cb + '(' + JSON.stringify(data) + ')' );
    });
    //獲取callback的內(nèi)容(函數(shù)名稱(chēng))篙顺,包裝之后返回給html。
  • 方法二:CORS

  • 優(yōu)勢(shì):

  • 整個(gè)過(guò)程無(wú)需用戶(hù)參與充择,完全由瀏覽器自己完成德玫;

  • 只需要在后臺(tái)加入響應(yīng)頭即可,不需要對(duì)ajax進(jìn)行復(fù)雜變換椎麦;

  • 劣勢(shì):

HTML端:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>新聞加載example</title>
    <style media="screen">
      .newsFrame{
        margin: 0 auto;
      }
    </style>
  </head>
  <body>
    <div class="newsFrame">
      <ul class="content">
        <li>在北大聽(tīng)講座</li>
        <li>統(tǒng)計(jì)陷阱</li>
        <li>淺薄</li>
      </ul>
      <button class="btn">換一批</button>
    </div>


     <script type="text/javascript">
        $('.btn').addEventListener('click',function(){

          var xmlhttp = new XMLHttpRequest();
          xmlhttp.open('get','http://b.har.com:8080/getNews',true);
          xmlhttp.send();

          xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState==4 && xmlhttp.status==200){
              appendhtml(JSON.parse(xmlhttp.responseText));
            }
          }


        })

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

      function $(id){
        return document.querySelector(id)
      }

    </script>
  </body>
</html>

后臺(tái)端:

app.get('/getNews', function(req, res) {

        var news = [
        "身邊的邏輯學(xué)",
        '牛奶可樂(lè)經(jīng)濟(jì)學(xué)',
        '看見(jiàn)',
        '論中國(guó)',
        '烏合之眾',
        '哲學(xué)的慰藉'
      ]
    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.head('Access-Control-Allow-Origin','http://a.har.com:8080')
    //注意這里是a.har.com:8080宰僧,因?yàn)楹笈_(tái)端是在b.har.com域下
    res.header("Access-Control-Allow-Origin","*");
    res.send(data);
  });
  • 方法三:降域

  • 優(yōu)勢(shì):

  • 代碼超級(jí)簡(jiǎn)單,只需一個(gè)命令就輕松搞定观挎;

  • 劣勢(shì):
    只能在擁有相同父域名下才可以使用琴儿;

a.har.com端:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>降域test</title>
    <style media="screen">
      .main{
        border: 1px solid #ccc;
        width:500px;
        height: 500px;
        display: inline-block;
        position: absolute;
        top:10px;
        left:10px;
      }
      iframe{
        border: 1px dashed #ccc;
        width:500px;
        height:500px;
        margin-left: 100px;
        position: absolute;
        top:10px;
        left:450px;
      }
    </style>
  </head>
  <body>
    <div class="ct">
      <div class="main">
        <h1>使用降域來(lái)實(shí)現(xiàn)跨域</h1>
        <input type="text" class="content" placeholder="http://a.har.com:8080">
      </div>
      <iframe src="http://b.har.com:8080/jiangyu2.html" frameborder="0"></iframe>
    </div>
    <script type="text/javascript">
      document.querySelector('.main input').addEventListener('input',function(){
        console.log(this.value);
        window.frames[0].document.querySelector('input').value = this.value;
      })
      document.domain = 'har.com';
      //降域的命令键兜;
    </script>
  </body>
</html>

b.har.com端:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>降域test2</title>
    <style media="screen">
  </style>
  </head>
  <body>
    <div class="ct">
      <h1>使用降域來(lái)實(shí)現(xiàn)跨域</h1>
      <div class="main">
        <input type="text" class="content" placeholder="http://a.har.com:8080">
      </div>
    </div>
    <script type="text/javascript">
      document.querySelector('.main input').addEventListener('input',function(){
        window.parent.document.querySelector('input').value = this.value;
      })
      document.domain = 'har.com';
      //降域的命令凤类;
    </script>
  </body>
</html>

-方法四:postMassage

  • 優(yōu)勢(shì):
  • 域名完全不相同也沒(méi)關(guān)系;
  • 劣勢(shì):
  • 操作真心復(fù)雜普气;

a.har.com:8080/postMessage端:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>降域test</title>
    <style media="screen">
      .main{
        border: 1px solid #ccc;
        width:500px;
        height: 500px;
        display: inline-block;
        position: absolute;
        top:10px;
        left:10px;
      }
      iframe{
        border: 1px dashed #ccc;
        width:500px;
        height:500px;
        margin-left: 100px;
        position: absolute;
        top:10px;
        left:450px;
      }
    </style>
  </head>
  <body>
    <div class="ct">
      <div class="main">
        <h1>使用postMessage來(lái)實(shí)現(xiàn)跨域</h1>
        <input type="text" class="content" placeholder="http://a.har.com:8080">
      </div>
      <iframe src="http://b.har.com:8080/postMessage2.html" frameborder="0"></iframe>
    </div>
    <script type="text/javascript">
      document.querySelector('.main input').addEventListener('input',function(){
        console.log(this.value);
        window.frames[0].postMessage(this.value,'*');
      })
      window.addEventListener('message',function(e){
        document.querySelector('.main input').value = e.data;
      })
    </script>
  </body>
</html>

b.har.com:8080/postMessage2端:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>降域test2</title>
    <style media="screen">
  </style>
  </head>
  <body>
    <div class="ct">
      <h1>使用postMessage來(lái)實(shí)現(xiàn)跨域</h1>
      <div class="main">
        <input type="text" class="content" placeholder="http://a.har.com:8080">
      </div>
    </div>
    <script type="text/javascript">
      document.querySelector('.main input').addEventListener('input',function(){
        window.parent.postMessage(this.value,'*');
      })
      window.addEventListener('message',function(e){
        document.querySelector('.main input').value = e.data;
        console.log(e.data);
      })
    </script>
  </body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末谜疤,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌夷磕,老刑警劉巖履肃,帶你破解...
    沈念sama閱讀 219,589評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異坐桩,居然都是意外死亡尺棋,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門(mén)绵跷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)膘螟,“玉大人,你說(shuō)我怎么就攤上這事碾局【2校” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,933評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵净当,是天一觀的道長(zhǎng)内斯。 經(jīng)常有香客問(wèn)我,道長(zhǎng)像啼,這世上最難降的妖魔是什么俘闯? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,976評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮忽冻,結(jié)果婚禮上真朗,老公的妹妹穿的比我還像新娘。我一直安慰自己甚颂,他們只是感情好蜜猾,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,999評(píng)論 6 393
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著振诬,像睡著了一般蹭睡。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上赶么,一...
    開(kāi)封第一講書(shū)人閱讀 51,775評(píng)論 1 307
  • 那天肩豁,我揣著相機(jī)與錄音,去河邊找鬼辫呻。 笑死清钥,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的放闺。 我是一名探鬼主播祟昭,決...
    沈念sama閱讀 40,474評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼怖侦!你這毒婦竟也來(lái)了篡悟?” 一聲冷哼從身側(cè)響起谜叹,我...
    開(kāi)封第一講書(shū)人閱讀 39,359評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎搬葬,沒(méi)想到半個(gè)月后荷腊,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,854評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡急凰,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,007評(píng)論 3 338
  • 正文 我和宋清朗相戀三年女仰,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抡锈。...
    茶點(diǎn)故事閱讀 40,146評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡疾忍,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出企孩,到底是詐尸還是另有隱情锭碳,我是刑警寧澤,帶...
    沈念sama閱讀 35,826評(píng)論 5 346
  • 正文 年R本政府宣布勿璃,位于F島的核電站,受9級(jí)特大地震影響推汽,放射性物質(zhì)發(fā)生泄漏补疑。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,484評(píng)論 3 331
  • 文/蒙蒙 一歹撒、第九天 我趴在偏房一處隱蔽的房頂上張望莲组。 院中可真熱鬧,春花似錦暖夭、人聲如沸锹杈。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,029評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)竭望。三九已至,卻和暖如春裕菠,著一層夾襖步出監(jiān)牢的瞬間咬清,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,153評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工奴潘, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留旧烧,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,420評(píng)論 3 373
  • 正文 我出身青樓画髓,卻偏偏與公主長(zhǎng)得像掘剪,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子奈虾,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,107評(píng)論 2 356

推薦閱讀更多精彩內(nèi)容