實現跨域的5種方法

一、jsonp

最多見的一種跨域方式,其背後原理就是利用了script標籤不受同源策略的限制,在頁面中動態插入了script,script標籤的src屬性就是後端api接口的地址,而且以get的方式將前端回調處理函數名稱告訴後端,後端在響應請求時會將回調返還,而且將數據以參數的形式傳遞回去。javascript

前端:html

複製代碼
//http://127.0.0.1:8888/jsonp.html
var script = document.createElement('script');
script.src = 'http://127.0.0.1:2333/jsonpHandler?callback=_callback'
document.body.appendChild(script);      //插入script標籤
//回調處理函數 _callback
var _callback = function(obj){
      for(key in obj){
        console.log('key: ' + key +' value: ' + obj[key]);
    }
}
複製代碼

後端:前端

複製代碼
//http://127.0.0.1:2333/jsonpHandler
app.get('/jsonpHandler', (req,res) => {
  let callback = req.query.callback;
  let obj = {
    type : 'jsonp',
    name : 'weapon-x'
  };
  res.writeHead(200, {"Content-Type": "text/javascript"});
  res.end(callback + '(' + JSON.stringify(obj) + ')');
})
複製代碼

二、CORS

Cross-Origin Resource Sharing(跨域資源共享)是一種容許當前域(origin)的資源(好比html/js/web service)被其餘域(origin)的腳本請求訪問的機制。
當使用XMLHttpRequest發送請求時,瀏覽器若是發現違反了同源策略就會自動加上一個請求頭:origin,後端在接受到請求後肯定響應後會在Response Headers中加入一個屬性:Access-Control-Allow-Origin,值就是發起請求的源地址(http://127.0.0.1:8888),瀏覽器獲得響應會進行判斷Access-Control-Allow-Origin的值是否和當前的地址相同,只有匹配成功後才進行響應處理。java

現代瀏覽器中和移動端都支持CORS(除了opera mini),IE下須要9+node

前端:
複製代碼
//http://127.0.0.1:8888/cors.html
var xhr = new XMLHttpRequest();
xhr.onload = function(data){
  var _data = JSON.parse(data.target.responseText)
  for(key in _data){
    console.log('key: ' + key +' value: ' + _data[key]);
  }
};
xhr.open('POST','http://127.0.0.1:2333/cors',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
複製代碼

後端:web

複製代碼
//http://127.0.0.1:2333/cors
app.post('/cors',(req,res) => {
  if(req.headers.origin){
    res.writeHead(200,{
      "Content-Type": "text/html; charset=UTF-8",
      "Access-Control-Allow-Origin":'http://127.0.0.1:8888'
    });
    let people = {
      type : 'cors',
      name : 'weapon-x'
    }
    res.end(JSON.stringify(people));
  }
})
複製代碼

三、服務器跨域

在先後端分離的項目中能夠藉助服務器實現跨域,具體作法是:前端向本地服務器發送請求,本地服務器代替前端再向api服務器接口發送請求進行服務器間通訊,本地服務器其實就是個中轉站的角色,再將響應的數據返回給前端,下面用node.js作一個示例json

前端:後端

複製代碼
//http://127.0.0.1:8888/server
var xhr = new XMLHttpRequest();
xhr.onload = function(data){
  var _data = JSON.parse(data.target.responseText)
  for(key in _data){
    console.log('key: ' + key +' value: ' + _data[key]);
  }
};
xhr.open('POST','http://127.0.0.1:8888/feXhr',true);  //向本地服務器發送請求   
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send("url=http://127.0.0.1:2333/beXhr");    //以參數形式告知須要請求的後端接口
複製代碼

後端:api

複製代碼
//http://127.0.0.1:8888/feXhr
app.post('/feXhr',(req,res) => {
  let url  = req.body.url;
  superagent.get(url)           //使用superagent想api接口發送請求
      .end(function (err,docs) {
          if(err){
              console.log(err);
              return
          }
          res.end(docs.res.text); //返回到前端
      })
})

//http://127.0.0.1:2333/beXhr
app.get('/beXhr',(req,res) => {
  let obj = {
    type : 'superagent',
    name : 'weapon-x'
  };
  res.writeHead(200, {"Content-Type": "text/javascript"});
  res.end(JSON.stringify(obj));     //響應
})
複製代碼

 

四、postmessage跨域

在HTML5中新增了postMessage方法,postMessage能夠實現跨文檔消息傳輸(Cross Document Messaging),Internet Explorer 8, Firefox 3, Opera 9, Chrome 3和 Safari 4都支持postMessage。
該方法能夠經過綁定window的message事件來監聽發送跨文檔消息傳輸內容。使用postMessage實現跨域的話原理就相似於jsonp,動態插入iframe標籤,再從iframe裏面拿回數據,私認爲用做跨頁面通訊更加適合跨域

語法:

originWindow.postMessage(message, targetOrigin);
originWindow:要發起請求的窗口引用 
message: 要發送出去的消息,能夠是字符串或者對象 
targetOrigin: 指定哪些窗口可以收到消息,其值能夠是字符串*(表示無限制)或者一個確切的URI

只有目標窗口的協議、主機地址或端口這三者所有匹配纔會發送消息。
  • 父窗口 b.com/index.html
    複製代碼
    <!DOCTYPE html>
    <html>
    <head>
        <title>Parent window</title>
    </head>
    <body>
    <div>
        <iframe id="child" src="http://a.com/index.html"></iframe>
    </div>
    <input id="p_input" type="txet" value="0">
    <button onclick='p_add()'>parent click to add</button>
    
    <script type="text/javascript">
        window.addEventListener('message',function(e){
            document.getElementById('p_input').value = e.data;
        });
    
        function p_add(){
          var p_input = document.getElementById('p_input');
          var value = +p_input.value+1;
          p_input.value= value;
          window.frames[0].postMessage(value,'http://a.com');
        }
    </script>
    </body>
    </html>
    複製代碼
  • 子窗口 a.com/index.html
    複製代碼
    <!doctype html>
    <html>
    <head>
        <title>Child window</title>
    </head>
    <body>
      <input id="c_input" type="text" value="0">
      <button onclick='c_add()'>child click to add</button>
    <script type="text/javascript">
        var c_input=document.getElementById('c_input');
    
        window.addEventListener('message', function(e) {
            if(e.source!=window.parent) return;
            var value = +c_input.value+1;
            c_input.value = value;
        });
    
        function c_add(){
            var value = +c_input.value+1;
            c_input.value = value;
            window.parent.postMessage(value,'http://b.com');
        }
    </script>
    </body>
    </html>
    複製代碼

     

5、修改document.domain跨子域

​ 前提條件:這兩個域名必須屬於同一個基礎域名!並且所用的協議,端口都要一致,不然沒法利用document.domain進行跨域,因此只能跨子域

​ 在根域範圍內,容許把domain屬性的值設置爲它的上一級域。例如,在」aaa.xxx.com」域內,能夠把domain設置爲 「xxx.com」 但不能設置爲 「xxx.org」 或者」com」。

如今存在兩個域名aaa.xxx.com和bbb.xxx.com。在aaa下嵌入bbb的頁面,因爲其document.name不一致,沒法在aaa下操做bbb的js。

能夠在aaa和bbb下經過js將document.name = 'xxx.com';設置一致,來達到互相訪問的做用。

 

原文連接有:

一、https://www.jianshu.com/p/a63c29e0c863

二、http://www.javashuo.com/article/p-tlwmmbxw-bb.html

相關文章
相關標籤/搜索