項(xiàng)目實(shí)戰(zhàn)之跨域處理~一文搞定所有跨域需求

什么是跨域?

跨域,是指瀏覽器不能執(zhí)行其他網(wǎng)站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對(duì)JavaScript實(shí)施的安全限制。
什么是同源策略?

同源策略(Same origin policy)是一種約定,它是瀏覽器最核心也最基本的安全功能,它是由Netscape提出的一個(gè)著名的安全策略。

同源策略是瀏覽器的行為,是為了保護(hù)本地?cái)?shù)據(jù)不被JavaScript代碼獲取回來(lái)的數(shù)據(jù)污染,因此攔截的是客戶(hù)端發(fā)出的請(qǐng)求回來(lái)的數(shù)據(jù)接收,即請(qǐng)求發(fā)送了,服務(wù)器響應(yīng)了,但是無(wú)法被瀏覽器接收。

其主要限制以下幾個(gè)方面:

    Cookie 、LocalStorage 和 IndexDB無(wú)法讀取
    無(wú)法獲取或操作另一個(gè)資源的DOM
    AJAX請(qǐng)求不能發(fā)送

那么什么是同源呢?所謂的同源,就是指兩個(gè)頁(yè)面具有相同的協(xié)議,主機(jī)(也常說(shuō)域名),端口,三個(gè)要素缺一不可。這樣可能不是很好理解,下面通過(guò)表格對(duì)比幫助大家理解:
 

   


















此時(shí),不允許同通信的頁(yè)面之間想要實(shí)現(xiàn)通信,就要使用到跨域了。

常見(jiàn)跨域方案

    1、 通過(guò)jsonp跨域
    2、 document.domain+iframe跨域
    3、 location.hash + iframe
    4、 window.name + iframe跨域
    5、 postMessage跨域
    6、 跨域資源共享(CORS)
    7、 nginx代理跨域
    8、 nodejs中間件代理跨域
    9、 WebSocket協(xié)議跨域

jsonp跨域

在頁(yè)面中通過(guò)script標(biāo)簽加載資源,是被瀏覽器所允許的,也不存在跨域的問(wèn)題,基于這一原理,我們可以通過(guò)動(dòng)態(tài)的創(chuàng)建過(guò)script標(biāo)簽,然后src賦值一個(gè)帶參的url,進(jìn)而實(shí)現(xiàn)跨域,也叫jsonp跨域。實(shí)現(xiàn)方式如下:
原生實(shí)現(xiàn)方式

function callback(res){
    console.log(res)//接口返回值
}

let jsonp = document.createElement('script');
jsonp.src = 'http:/www.monkey.com/admin/getUser?name=小燕子&callback=callback';

document.getElementsByTagName('head')[0].appendChild(jsonp);//添加到頁(yè)面中

jsonp.remove();//從頁(yè)面中移除

 

jQuery實(shí)現(xiàn)

    第一種:$.ajax()方法

$.ajax({
    url:'http:/www.monkey.com/admin/getUser',
    dataType:"jsonp",
    jsonp: "callback",//請(qǐng)求時(shí)路徑參數(shù)名
    jsonpCallback:"callback",//設(shè)置后端返回函數(shù)名
    success:function(data){//回調(diào)函數(shù)
        console.log(data);
    }
});

 

    第二種:$.get()方法


$.get('http:/www.monkey.com/admin/getUser', {各種數(shù)據(jù)}, function(data) {
    console.log(data);
}, 'jsonp');

 

    推薦使用$.get()方法

后端node.js核心代碼示例:

// jsonp返回設(shè)置
res.writeHead(200,{'Content-Type':'text/javascript'});
res.write(callback+'('+JSON..stringify(response) + ')');

 

    jsonp跨域只能實(shí)現(xiàn)get請(qǐng)求

document.domain+iframe跨域

運(yùn)用此方法跨域必須有個(gè)前提:

這兩個(gè)域名必須屬于同一個(gè)一級(jí)域名!而且所用的協(xié)議,端口都要一致,否則無(wú)法利用document.domain進(jìn)行跨域。

Javascript出于對(duì)安全性的考慮,而禁止兩個(gè)或者多個(gè)不同域的頁(yè)面進(jìn)行互相操作。
而相同域的頁(yè)面在相互操作的時(shí)候不會(huì)有任何問(wèn)題。

實(shí)現(xiàn)方式:

    父頁(yè)面(http://www.monkey.com/a.html)

<iframe id='iframe' src='http://monkey.com/b.html'></iframe>

<script>
    document.domain = 'monkey.com';
    var name = 'monkeysoft'
</script>

 

    子頁(yè)面(http://monkey.com/b.html)

<script>
    document.domain = 'monkey.com';
    console.log(window.parent.name)//monkeysoft
</script>

 

location.hash + iframe

當(dāng)兩個(gè)不同域的頁(yè)面之間想要實(shí)現(xiàn)通信的時(shí)候,可以通過(guò)與其中一個(gè)頁(yè)面同域的第三個(gè)頁(yè)面實(shí)現(xiàn)。因?yàn)楦淖僪ash值,不會(huì)刷新頁(yè)面,所以可以通過(guò)hash值進(jìn)行傳遞參數(shù)。

畫(huà)個(gè)草圖幫助理解:

實(shí)現(xiàn)方式:

    a.html(http://www.monkey.com/a.html)

<iframe id="iframe" src="http://www.monkey1.com/b.html" style="display:none;"></iframe>

<script>
    var iframe = document.getElementById('iframe');

    // 向b.html傳hash值
    setTimeout(function() {
        iframe.src = iframe.src + '#name=monkey';
    }, 1000);
    
    // 開(kāi)放給同域c.html的回調(diào)方法
    function onCallback(res) {
        console('data from c.html ---> ' + res);
    }
</script>

 

    b.html(http://www.monkey1.com/b.html)

<iframe id="iframe" src="http://www.monkey.com/c.html" style="display:none;"></iframe>

<script>
    var iframe = document.getElementById('iframe');

    // 監(jiān)聽(tīng)a.html傳來(lái)的hash值,再傳給c.html
    window.onhashchange = function () {
        iframe.src = iframe.src + location.hash;
    };
</script>

 

    c.html(http://www.monkey.com/c.html)

<script>
    // 監(jiān)聽(tīng)b.html傳來(lái)的hash值
    window.onhashchange = function () {
        // 再通過(guò)操作同域a.html的js回調(diào),將結(jié)果傳回
        window.parent.parent.onCallback('hello: ' + location.hash.replace('#name=', ''));
    };
</script>

 

    此方法有個(gè)缺點(diǎn),就是所有傳遞的數(shù)據(jù)都暴露在了url中。

window.name + iframe跨域

window.name的值再不同的頁(yè)面(包括不同域名)加載后依然存在,并且支持的數(shù)據(jù)量非??捎^,最大2MB。

    簡(jiǎn)單來(lái)說(shuō)就是頁(yè)面刷新之后,window.name值依舊存在






因此我們可以基于這個(gè)原理,我們可以巧妙的實(shí)現(xiàn)跨域,并且同時(shí)它也是安全操作。

實(shí)現(xiàn)方式:

    a.html(http://www.monkey.com/a.html)

var proxy = function(url, callback) {
    var state = 0;
    var iframe = document.createElement('iframe');

    // 加載跨域頁(yè)面
    iframe.src = url;

    // onload事件會(huì)觸發(fā)2次,第1次加載跨域頁(yè),并留存數(shù)據(jù)于window.name
    iframe.onload = function() {
        if (state === 1) {
            // 第2次onload(同域proxy頁(yè))成功后,讀取同域window.name中數(shù)據(jù)
            callback(iframe.contentWindow.name);
            destoryFrame();

        } else if (state === 0) {
            // 第1次onload(跨域頁(yè))成功后,切換到同域代理頁(yè)面
            iframe.contentWindow.location = 'http://www.domain1.com/proxy.html';
            state = 1;
        }
    };

    document.body.appendChild(iframe);

    // 獲取數(shù)據(jù)以后銷(xiāo)毀這個(gè)iframe,釋放內(nèi)存;這也保證了安全(不被其他域frame js訪(fǎng)問(wèn))
    function destoryFrame() {
        iframe.contentWindow.document.write('');
        iframe.contentWindow.close();
        document.body.removeChild(iframe);
    }
};

// 請(qǐng)求跨域b頁(yè)面數(shù)據(jù)
proxy('http://www.domain2.com/b.html', function(data){
    alert(data);
});

 

    proxy.html(http://www.monkey.com/proxy.html)

中間代理頁(yè),與a.html同域,內(nèi)容為空即可。

    b.html(http://www.monkey1.com/b.html)

<script>
    window.name = 'monkey1';
</script>

 

postMessage跨域

隨著HTML5的發(fā)展,html5工作組提供了兩個(gè)重要的接口:postMessage(send) 和 onmessage。這兩個(gè)接口有點(diǎn)類(lèi)似于websocket,可以實(shí)現(xiàn)兩個(gè)跨域站點(diǎn)頁(yè)面之間的數(shù)據(jù)傳遞。

postMessage(data,origin),接收兩個(gè)參數(shù):

    data是傳輸?shù)臄?shù)據(jù),部分瀏覽器只支持字符串,因此最好傳參時(shí)使用JSON.stringify()序列化。

    origin: 協(xié)議+主機(jī)+端口號(hào),也可以設(shè)置為"*",表示可以傳遞給任意窗口,如果要指定和當(dāng)前窗口同源的話(huà)設(shè)置為"/"。

實(shí)現(xiàn)方式:

    a.html(http://www.monkey.com/a.html)

<iframe id="iframe" src="http://www.monkey1.com/b.html" style="display:none;"></iframe>
<script>       
    var iframe = document.getElementById('iframe');
    iframe.onload = function() {
        var data = {
            name: 'monkeysoft'
        };
        // 向monkey1傳送跨域數(shù)據(jù)
        iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.monkey1.com');
    };

    // 接受monkey1返回?cái)?shù)據(jù)
    window.addEventListener('message', function(e) {
        alert('data from monkey1 ---> ' + e.data);
    }, false);
</script>

 

    b.html(http://www.monkey1.com/b.html)

<script>
    // 接收monkey的數(shù)據(jù)
    window.addEventListener('message', function(e) {
        alert('data from monkey ---> ' + e.data);

        var data = JSON.parse(e.data);
        if (data) {
            data.number = 16;
            // 處理后再發(fā)回monkey
            window.parent.postMessage(JSON.stringify(data), 'http://www.monkey.com');
        }
    }, false);
</script>

 

跨域資源共享(CORS)

只需要服務(wù)端設(shè)置Access-Control-Allow-Origin即可,前端無(wú)須設(shè)置
nginx反向代理跨域

nginx在本地搭建一個(gè)服務(wù)向遠(yuǎn)程服務(wù)器請(qǐng)求數(shù)據(jù),前提是前后端分離的條件下,這樣后端可以上傳他的接口到服務(wù)器,或者你可以訪(fǎng)問(wèn)后臺(tái)本地的環(huán)境也是可以的。

    下載nginx

http://nginx.org/en/download.html

下載任意一個(gè)版本即可,我下載的是nginx-1.12.2,下載之后解壓即可。

    配置代理

server {
        listen       8080;
        server_name  localhost;
        
        #charset koi8-r;
        access_log  logs/k8s.log;
        
        location / {
            root   D:/_test/front/app;  #你項(xiàng)目的根目錄
            index  index.html index.htm;
        }
        
        ## 用戶(hù)訪(fǎng)問(wèn) localhost/api,則反向代理到http://www.monkeysoft.com
        location /api/ {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host  $http_host;
            proxy_set_header X-Nginx-Proxy true;
            proxy_set_header Connection "";
            proxy_pass   http://www.monkeysoft.com;  #****這里填上服務(wù)器地址
            proxy_redirect default ;
        }
}

 

    啟動(dòng)服務(wù)

配置好了啟動(dòng)nginx服務(wù)器就好了。在這里整理一些windows常用的命令:

1、啟動(dòng):
D:\nginx-1.12.2>start nginx或
D:\nginx-1.12.2>nginx.exe

2、停止:
D:\nginx-1.12.2>nginx.exe -s stop或
D:\nginx-1.12.2>nginx.exe -s quit
注:stop是快速停止nginx,可能并不保存相關(guān)信息;quit是完整有序的停止nginx,并保存相關(guān)信息。

3、重新載入Nginx:
D:\nginx-1.12.2>nginx.exe -s reload
當(dāng)配置信息修改,需要重新載入這些配置時(shí)使用此命令。


4、重新打開(kāi)日志文件:
D:\nginx-1.12.2>nginx.exe -s reopen

5、查看Nginx版本:
D:\nginx-1.12.2>nginx -v

 

服務(wù)器代理跨域

服務(wù)器代理一般是通過(guò)node中間件http-proxy-middleware實(shí)現(xiàn)的,在vue、react腳手架中,已經(jīng)集成了該中間件,我們只需要配置使用既可。

webpack配置文件部分代碼:

devServer: {
    proxy: {
      '/api': {
        target: 'http://www.monkey.com:8080',//真實(shí)請(qǐng)求地址
        changeOrigin: true, // 默認(rèn)false,是否需要改變?cè)贾鳈C(jī)頭為目標(biāo)URL
        ws: true,// 是否代理websocket
        pathRewrite: {//重寫(xiě)路徑
          '^/api': ''
        },
        router: {
             // 如果請(qǐng)求主機(jī) == 'dev.localhost:3000',
             // 重寫(xiě)目標(biāo)服務(wù)器 'http://www.example.org' 為 'http://localhost:8000'
             'dev.localhost:3000' : 'http://localhost:8000'
        }
      },
    }
},

 

WebSocket協(xié)議跨域。

WebSocket protocol是HTML5一種新的協(xié)議。它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工通信,同時(shí)允許跨域通訊,是server push技術(shù)的一種很好的實(shí)現(xiàn)。

實(shí)現(xiàn)方式

頁(yè)面端(客戶(hù)端):

<script>
    var ws = new WebSocket('ws://localhost:8080');
    ws.onmessage = function (message) {
        console.log(message);//接收消息
        
    };
    
    
    //發(fā)送消息
    var message = {
        name:'monkeysoft'
    }
    
    ws.send(JSON.stringify(message));
</script>

 

服務(wù)端(node):

//引入http標(biāo)準(zhǔn)模塊,CommonJS模塊

const http = require("http");
const fs = require("fs");
const ws = require("socket.io");

//創(chuàng)建一個(gè)web服務(wù)

const server  = http.createServer(function(request,response){
  response.writeHead(200,{
    "Content-type":"text/html;charset=UTF-8"
  })
    // 可發(fā)送文本
    // response.end("hello world");
    
    // 可自動(dòng)解析html
     response.end("<h1>我是標(biāo)題2</h1>");
})

//基于當(dāng)前web服務(wù)開(kāi)啟socket實(shí)例
const io = ws(server)

//檢測(cè)連接事件
io.on("connection",function(socket){

  //接收客戶(hù)端所發(fā)送的消息
  socket.on("message",function(message){
    console.log(message)
    //向所有客戶(hù)端廣播該消息
    io.emit("message",message)
  })
  //監(jiān)聽(tīng)到斷開(kāi)鏈接
  socket.on("disconnect",function(){
    //發(fā)送廣播  某用戶(hù)離開(kāi)了群聊
    
  })
})

//服務(wù)端監(jiān)聽(tīng)端口
 server.listen(8080)
 


歡迎關(guān)注微信公眾號(hào):猴哥說(shuō)前端