1、jsonp
最常見的一種跨域方式,其背后原理就是利用了script標簽不受同源策略的限制,在頁面中動態插入了script,script標簽的src屬性就是后端api接口的地址,並且以get的方式將前端回調處理函數名稱告訴后端,后端在響應請求時會將回調返還,並且將數據以參數的形式傳遞回去。
前端:
//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) + ')'); })
2、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的值是否和當前的地址相同,只有匹配成功后才進行響應處理。
現代瀏覽器中和移動端都支持CORS(除了opera mini),IE下需要9+
//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();
后端:
//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)); } })
3、服務器跨域
在前后端分離的項目中可以借助服務器實現跨域,具體做法是:前端向本地服務器發送請求,本地服務器代替前端再向api服務器接口發送請求進行服務器間通信,本地服務器其實就是個中轉站的角色,再將響應的數據返回給前端,下面用node.js做一個示例
前端:
//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"); //以參數形式告知需要請求的后端接口
后端:
//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)); //響應 })
4、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>
五、修改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';設置一致,來達到互相訪問的作用。