前端跨域總結

聲明

本人也在不斷的學習和積累中,文章中有不足和誤導的地方還請見諒,可以給我留言指正。希望和大家共同進步,共建和諧學習環(huán)境。

跨域

?1、什么是跨域

指的是瀏覽器不能執(zhí)行其他網(wǎng)站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對javascript施加的安全限制。

?2、同源策略

是指協(xié)議,域名,端口都要相同,其中有一個不同都會產(chǎn)生跨域;


跨域示例
?3、同源策略限制以下行為:
  • Cookie、LocalStorage 和 IndexDB 無法讀取
  • DOM 和 JS 對象無法獲取
  • Ajax請求發(fā)送不出去

解決方案

?據(jù)我了解的,總結了以下幾種方式,有其他方式的可以給我留言:
  • domain設置,只適用于子域
  • jsonp方法,只適用于get請求
  • CROS,(跨域資源共享協(xié)議),適用于各種請求
  • post Message,適用于父子網(wǎng)頁iframe通信
  • location.hash, 數(shù)據(jù)直接暴露在了url中,數(shù)據(jù)容量和類型都有限
  • Nginx 代理
?1、domain

??假設我們現(xiàn)在有一個頁面 a.html 它的地址為http://www.a.com/a.html , 在a.html 在中有一個iframe,iframe的src為http://a.com/b.html,這個頁面與它里面的iframe框架是不同域的,所以我們是無法通過在頁面中書寫js代碼來獲取iframe中的東西的;
??a.html內容:

<script type="text/javascript">
    function test(){
        var iframe = document.getElementById('ifame');
        var win = document.contentWindow;
        var doc = win.document;//這里獲取不到iframe里的document對象
        var name = win.name;//這里同樣獲取不到window對象的name屬性
    }
</script>
<iframe id = "iframe" src="http://a.com/b.html" onload = "test()"></iframe>

??使用domain設置,a.html中的內容修改為:

<iframe id = "iframe" src="http://a.com/b.html" onload = "test()"></iframe>
<script type="text/javascript">
    document.domain = 'a.com'; //設置成主域
    function test(){
        alert(document.getElementById('iframe').contentWindow);  //contentWindow 可取得子窗口的 window 對象
    }
</script>

??在b.html 中也設置

<script type="text/javascript">
    document.domain = 'a.com';//在iframe載入這個頁面也設置document.domain,使之與主頁面的document.domain相同
</script>
?2、jsonp

??采用這種方法,是由于html標簽src屬性不受同源限制。
??優(yōu)點:它不像XMLHttpRequest對象實現(xiàn)的Ajax請求那樣受到同源策略的限制;它的兼容性更好,在更加古老的瀏覽器中都可以運行,不需要XMLHttpRequest或ActiveX的支持;并且在請求完畢后可以通過調用callback的方式回傳結果。
??缺點:它只支持GET請求而不支持POST等其它類型的HTTP請求;它只支持跨域HTTP請求這種情況,不能解決不同域的兩個頁面之間如何進行JavaScript調用的問題。

??原生方法:

function jsonp({url,callback}) {
  let script = document.createElement('script');
  script.src = `${url}&callback=${callback}`;
  document.head.appendChild(script);
}

??node服務:

const http = require('http');
const url = require('url');
const queryString = require('querystring');
const data = JSON.stringify({
  title: 'hello,jsonp!'
})

const server = http.createServer((request, response) => {
  let addr = url.parse(request.url);
  if (addr.pathname == '/jsonp') {
    let cb = queryString.parse(addr.query).callback;
    response.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' })
    response.write(cb + '('+ data +')'); // 回調
  } else {
    response.writeHead(403, { 'Content-Type': 'text/plain;charset=utf-8' })
    response.write('403');
  }
  response.end();
})

server.listen(3000, () => {
  console.log('Server is running on port 3000!');
})

??頁面調用:

jsonp({
  url: 'http://localhost:3000/jsonp?from=1',
  callback: 'getData',
})

function getData(res) {
  console.log(res); // {title: "hello,jsonp!"}
}

??jQuery方法:

$(function () {  
  $.ajax({
    url: 'http://localhost:3000/jsonp?from=1',
    type: 'get',
    dataType: 'jsonp',
    success: function(res) {
      console.log(res); // {title: "hello,jsonp!"}
    }
  })
})
?3、CROS

??CORS(Cross -Origin Resource Sharing),跨域資源共享,是一個W3C標準,在http的基礎上發(fā)布的標準協(xié)議。
??CORS需要游覽器和服務器同時支持,解決了游覽器的同源限制,使得跨域資源請求得以實現(xiàn)。它有兩種請求,一種是簡單請求,另外一種是非簡單請求。
簡單請求
滿足以下兩個條件就屬于簡單請求,反之非簡單。

  1. 請求方式是 GET、POST、HEAD;
  2. 響應頭信息是 Accept、Accept-Language、Content-Language、Last-Event-ID、Content-Type(只限于application/x-www-form-urlencoded、multipart/form-data、text/plain);
  • 簡單請求
    有三個CORS字段需要加在響應頭中,前面部分都是以Access-Control開頭:

? 1、Access-Control-Allow-Origin,這個表示接受哪些域名的請求,如果是*號,那就是任何域名都可以請求;
? 2、Access-Control-Allow-Credentials,這個表示是否允許攜帶cookie,默認是false,不允許攜帶;

? ? 如果設置為true, 要發(fā)送cookie,允許域就必須指定域名方法;客戶端http請求必須設置:

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

? 3、Access-Control-Expose-Headers,這個表示服務器可接受的響應頭字段,如果客戶端發(fā)送過來請求攜帶的Cache-Control、Content-Language、Content-Type、Expires、Last-Modified,還有自定義請求頭字段。

  • 非簡單請求

? 就是除了簡單請求的幾種方法外,比如說PUT請求、DELETE請求,這種都是要發(fā)一個預檢請求的,然后服務器允許,才會發(fā)送真正的請求。

? 非簡單請求有以下幾個字段需要傳遞:
? 1、Access-Control-Allow-Methods,值是以逗號分隔,比如:GET,POST,DELETE;
? 2、Access-Control-Allow-Headers,值是默認字段或者自定義字段,例如:X-Auth-Info;
? 3、Access-Control-Allow-Credentials,是否攜帶cookie信息;
? 4、Access-Control-Max-Age,代表預檢請求的有效期限,單位是秒。

?4、post Message
  • otherWindow.postMessage(message, targetOrigin);

otherWindow:指目標窗口,也就是給哪個window發(fā)消息,是 window.frames 屬性的成員或者由 window.open 方法創(chuàng)建的窗口
message: 是要發(fā)送的消息,類型為 String、Object (IE8、9 不支持)
targetOrigin: 是限定消息接收范圍,不限制請使用 ‘*

??父頁面通過postMessage('<msg>','<url>'),子頁面接收消息,并且返回消息到父頁面,父頁面監(jiān)聽message事件接收消息。
??例如:http://map.domaintest.org:8089/parent.html發(fā)送消息給子頁面http://map.domaintest.org:8089/son.html,子頁面返回消息。

  • 父頁面的:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>父級頁面</title>
</head>
<body>
  <button id="btn">發(fā)送消息</button>
  <iframe id="child" src="http://map.domaintest.org:8089/son.html" width="100%" height="300"></iframe>
  <script>
    let sendBtn = document.querySelector('#btn');
    sendBtn.addEventListener('click', sendMsg, false);
    function sendMsg () {  
      window.frames[0].postMessage('getMsg', 'http://map.domaintest.org:8089/son.html');
    }
    window.addEventListener('message', function (e) {
      let data = e.data;
      console.log('接收到的消息是:'+ data);
    })
  </script>
</body>
</html>
  • 子頁面的:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>子頁面</title>
</head>
<body>
  <h2>窗口</h2>
  <p>我是另外一個窗口!</p>
  <script>
    window.addEventListener('message', function (e) {  
      if (e.source != window.parent) return;
      window.parent.postMessage('我是來自子頁面的消息!', '*');
    }, false)
  </script>
</body>
</html>
?5、location.hash

?原理:父窗口可以對iframe進行URL讀寫,iframe也可以讀寫父窗口的URL,動態(tài)插入一個iframe然后設置其src為服務端地址,而服務端同樣輸出一端js代碼,也同時通過與子窗口之間的通信來完成數(shù)據(jù)的傳輸。
?假如父頁面是baidu.com/a.html,iframe嵌入的頁面為google.com/b.html(此處省略了域名等url屬性),要實現(xiàn)此兩個頁面間的通信可以通過以下方法。

  • a.html傳送數(shù)據(jù)到b.html
  • a.html下修改iframe的src為google.com/b.html#paco
  • b.html監(jiān)聽到url發(fā)生變化,觸發(fā)相應操作
  • b.html傳送數(shù)據(jù)到a.html,由于兩個頁面不在同一個域下IE、Chrome不允許修改parent.location.hash的值,所以要借助于父窗口域名下的一個代理iframe
  • b.html下創(chuàng)建一個隱藏的iframe,此iframe的src是baidu.com域下的,并掛上要傳送的hash數(shù)據(jù),如src=”http://www.baidu.com/proxy.html#data
  • proxy.html監(jiān)聽到url發(fā)生變化,修改a.html的url(因為a.html和proxy.html同域,所以proxy.html可修改a.html的url hash)
  • a.html監(jiān)聽到url發(fā)生變化,觸發(fā)相應操作

?b.html內容:

try {  
    parent.location.hash = 'data';  
} catch (e) {  
    // ie、chrome的安全機制無法修改parent.location.hash,  
    var ifrproxy = document.createElement('iframe');  
    ifrproxy.style.display = 'none';  
    ifrproxy.src = "http://www.baidu.com/proxy.html#data";  
    document.body.appendChild(ifrproxy);  
}

?proxy.html內容:

//因為parent.parent(即baidu.com/a.html)和baidu.com/proxy.html屬于同一個域,所以可以改變其location.hash的值  
parent.parent.location.hash = self.location.hash.substring(1);
?6、Nginx配置

??利用nginx作為反向代理

server {
    listen      80; #監(jiān)聽80端口,可以改成其他端口
    server_name  localhost; # 當前服務的域名
    #charset koi8-r;
    #access_log  logs/host.access.log  main;

    location / {
        proxy_pass http://localhost:81;
        proxy_redirect default;
    }

   location /apis { #添加訪問目錄為/apis的代理配置
       rewrite  ^/apis/(.*)$ /$1 break;
       proxy_pass  http://localhost:82;
   }
   #....省略下面的配置
}

參考

知乎-前端跨域知識總結
CSDN-前端跨域知識總結

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 前言 關于前端跨域的解決方法的多種多樣實在讓人目不暇接。以前碰到一個公司面試的場景是這樣的,好幾個人一起在等待面試...
    andreaxiang閱讀 526評論 1 4
  • 轉載:http://damonare.github.io/2016/10/30/%E5%89%8D%E7%AB%A...
    壯哉我大前端閱讀 577評論 2 9
  • 1. 什么是跨域? 跨域一詞從字面意思看,就是跨域名嘛,但實際上跨域的范圍絕對不止那么狹隘。具體概念如下:只要協(xié)議...
    開車去環(huán)游世界閱讀 609評論 0 0
  • 前言相信每一個前端er對于跨域這兩個字都不會陌生,在實際項目中應用也是比較多的。但跨域方法的多種多樣實在讓人目不暇...
    Www劉閱讀 728評論 2 23
  • 前端開發(fā)中,跨域使我們經(jīng)常遇到的一個問題,也是面試中經(jīng)常被問到的一些問題,所以,這里,我們做個總結。小小問題,不足...
    Nealyang閱讀 514評論 0 0

友情鏈接更多精彩內容