- 什么是跨域
- JSONP
- proxy代理
- cors
- xdr
由於瀏覽器同源策略,凡是發送請求url的協議、域名、端口三者之間任意一與當前頁面地址不同即為跨域。具體可以查看下表(來源)
JSONP
這種方式主要是通過動態插入一個script標簽。瀏覽器對script的資源引用沒有同源限制,同時資源加載到頁面后會立即執行(沒有阻塞的情況下)。
1 <script> 2 var _script = document.createElement('script'); 3 _script.type = "text/javascript"; 4 _script.src = "http://localhost:8888/jsonp?callback=f"; 5 document.head.appendChild(_script); 6 </script>
實際項目中JSONP通常用來獲取json格式數據,這時前后端通常約定一個參數callback,該參數的值,就是處理返回數據的函數名稱。

1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"> 6 <title>jsonp_test</title> 7 8 <script> 9 var f = function(data){ 10 alert(data.name); 11 } 12 /*var xhr = new XMLHttpRequest(); 13 xhr.onload = function(){ 14 alert(xhr.responseText); 15 }; 16 xhr.open('POST', 'http://localhost:8888/cors', true); 17 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 18 xhr.send("f=json");*/ 19 </script> 20 21 <script> 22 var _script = document.createElement('script'); 23 _script.type = "text/javascript"; 24 _script.src = "http://localhost:8888/jsonp?callback=f"; 25 document.head.appendChild(_script); 26 </script> 27 </head>

1 var query = _url.query; 2 console.log(query); 3 var params = qs.parse(query); 4 console.log(params); 5 var f = ""; 6 7 f = params.callback; 8 9 res.writeHead(200, {"Content-Type": "text/javascript"}); 10 res.write(f + "({name:'hello world'})"); 11 res.end();
缺點:
1、這種方式無法發送post請求(這里)
2、另外要確定jsonp的請求是否失敗並不容易,大多數框架的實現都是結合超時時間來判定。
Proxy代理
這種方式首先將請求發送給后台服務器,通過服務器來發送請求,然后將請求的結果傳遞給前端。

1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"> 6 <title>proxy_test</title> 7 8 <script> 9 var f = function(data){ 10 alert(data.name); 11 } 12 var xhr = new XMLHttpRequest(); 13 xhr.onload = function(){ 14 alert(xhr.responseText); 15 }; 16 xhr.open('POST', 'http://localhost:8888/proxy?http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer', true); 17 xhr.send("f=json"); 18 </script> 19 </head> 20 21 <body> 22 </body> 23 </html>

1 var proxyUrl = ""; 2 if (req.url.indexOf('?') > -1) { 3 proxyUrl = req.url.substr(req.url.indexOf('?') + 1); 4 console.log(proxyUrl); 5 } 6 if (req.method === 'GET') { 7 request.get(proxyUrl).pipe(res); 8 } else if (req.method === 'POST') { 9 var post = ''; //定義了一個post變量,用於暫存請求體的信息 10 11 req.on('data', function(chunk){ //通過req的data事件監聽函數,每當接受到請求體的數據,就累加到post變量中 12 post += chunk; 13 }); 14 15 req.on('end', function(){ //在end事件觸發后,通過querystring.parse將post解析為真正的POST請求格式,然后向客戶端返回。 16 post = qs.parse(post); 17 request({ 18 method: 'POST', 19 url: proxyUrl, 20 form: post 21 }).pipe(res); 22 }); 23 }
需要注意的是如果你代理的是https協議的請求,那么你的proxy首先需要信任該證書(尤其是自定義證書)或者忽略證書檢查,否則你的請求無法成功。12306就提供了一個鮮活的例子。
還需要注意一點,對於同一請求瀏覽器通常會從緩存中讀取數據,我們有時候不想從緩存中讀取,所以會加一個preventCache參數,這個時候請求url變成:url?preventCache=12345567....;這本身沒有什么問題,問題出在當使用某些前端框架(比如jquery)發送proxy代理請求時,請求url為proxy?url,同時設置preventCache:true,框架不能正確處理這個參數,結果發出去的請求變成proxy?url&preventCache=123456(正長應為proxy?url?preventCache=12356);后端截取后發送的請求為url&preventCache=123456,根本沒有這個地址,所以你得不到正確結果。
CORS
這是現代瀏覽器支持跨域資源請求的一種方式。
當你使用XMLHttpRequest發送請求時,瀏覽器發現該請求不符合同源策略,會給該請求加一個請求頭:Origin,后台進行一系列處理,如果確定接受請求則在返回結果中加入一個響應頭:Access-Control-Allow-Origin;瀏覽器判斷該相應頭中是否包含Origin的值,如果有則瀏覽器會處理響應,我們就可以拿到響應數據,如果不包含瀏覽器直接駁回,這時我們無法拿到響應數據。

1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"> 6 <title>jsonp_test</title> 7 8 <script> 9 /*var f = function(data){ 10 alert(data.name); 11 }*/ 12 var xhr = new XMLHttpRequest(); 13 xhr.onload = function(){ 14 alert(xhr.responseText); 15 }; 16 xhr.open('POST', 'http://localhost:8888/cors', true); 17 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 18 xhr.send("f=json"); 19 </script> 20 21 <script> 22 /* var _script = document.createElement('script'); 23 _script.type = "text/javascript"; 24 _script.src = "http://localhost:8888/jsonp?callback=f"; 25 document.head.appendChild(_script);*/ 26 </script> 27 </head> 28 29 <body> 30 </body> 31 </html>

1 if (req.headers.origin) { 2 3 res.writeHead(200, { 4 "Content-Type": "text/html; charset=UTF-8", 5 "Access-Control-Allow-Origin":'http://localhost'/*, 6 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 7 'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'*/ 8 }); 9 res.write('cors'); 10 res.end(); 11 }
如果我們把Access-Control-Allow-Origin去掉,瀏覽器會駁回響應,我們也就拿不到數據。
需要注意的一點是Preflighted Request的透明服務器驗證機制支持開發人員使用自定義的頭部、GET或POST之外的方法,以及不同類型的主題內容。總結如如:
1、非GET 、POST請求
2、POST請求的content-type不是常規的三個:application/x- www-form-urlencoded(使用 HTTP 的 POST 方法提交的表單)、multipart/form-data(同上,但主要用於表單提交時伴隨文件上傳的場合)、text/plain(純文本)
3、POST請求的payload為text/html
4、設置自定義頭部
OPTIONS請求頭部中會包含以下頭部:Origin、Access-Control-Request-Method、Access-Control-Request-Headers,發送這個請求后,服務器可以設置如下頭部與瀏覽器溝通來判斷是否允許這個請求。
Access-Control-Allow-Origin、Access-Control-Allow-Method、Access-Control-Allow-Headers

1 var xhr = new XMLHttpRequest(); 2 xhr.onload = function(){ 3 alert(xhr.responseText); 4 }; 5 xhr.open('POST', 'http://localhost:8888/cors', true); 6 xhr.setRequestHeader("Content-Type", "text/html"); 7 xhr.send("f=json");

1 if (req.headers.origin) { 2 3 res.writeHead(200, { 4 "Content-Type": "text/html; charset=UTF-8", 5 "Access-Control-Allow-Origin":'http://localhost', 6 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS', 7 'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type'/**/ 8 }); 9 res.write('cors'); 10 res.end(); 11 }
如果你在調試狀態,你會發現后台代碼執行了兩遍,說明發送了兩次請求。注意一下我們的onload代碼只執行了一次,所以說OPTIONS請求對程序來說是透明的,他的請求結果會被緩存起來。
如果我們修改一下后台代碼,把Content-Type去掉,你會發現OPTIONS請求失敗。
通過setRequestHeader('X-Request-With', null)可以避免瀏覽器發送OPTIONS請求。
根據我的測試,當使用cors發送跨域請求時失敗時,后台是接收到了這次請求,后台可能也執行了數據查詢操作,只是響應頭部不合符要求,瀏覽器阻斷了這次請求。
XDR
這是IE8、IE9提供的一種跨域解決方案,功能較弱只支持get跟post請求,而且對於協議不同的跨域是無能為力的,比如在http協議下發送https請求。看一下微軟自己的例子就行

1 <!DOCTYPE html> 2 3 <html> 4 <body> 5 <h2>XDomainRequest</h2> 6 <input type="text" id="tbURL" value="http://www.contoso.com/xdr.txt" style="width: 300px"><br> 7 <input type="text" id="tbTO" value="10000"><br> 8 <input type="button" onclick="mytest()" value="Get"> 9 <input type="button" onclick="stopdata()" value="Stop"> 10 <input type="button" onclick="readdata()" value="Read"> 11 <br> 12 <div id="dResponse"></div> 13 <script> 14 var xdr; 15 function readdata() 16 { 17 var dRes = document.getElementById('dResponse'); 18 dRes.innerText = xdr.responseText; 19 alert("Content-type: " + xdr.contentType); 20 alert("Length: " + xdr.responseText.length); 21 } 22 23 function err() 24 { 25 alert("XDR onerror"); 26 } 27 28 function timeo() 29 { 30 alert("XDR ontimeout"); 31 } 32 33 function loadd() 34 { 35 alert("XDR onload"); 36 alert("Got: " + xdr.responseText); 37 } 38 39 function progres() 40 { 41 alert("XDR onprogress"); 42 alert("Got: " + xdr.responseText); 43 } 44 45 function stopdata() 46 { 47 xdr.abort(); 48 } 49 50 function mytest() 51 { 52 var url = document.getElementById('tbURL'); 53 var timeout = document.getElementById('tbTO'); 54 if (window.XDomainRequest) 55 { 56 xdr = new XDomainRequest(); 57 if (xdr) 58 { 59 xdr.onerror = err; 60 xdr.ontimeout = timeo; 61 xdr.onprogress = progres; 62 xdr.onload = loadd; 63 xdr.timeout = tbTO.value; 64 xdr.open("get", tbURL.value); 65 xdr.send(); 66 } 67 else 68 { 69 alert("Failed to create"); 70 } 71 } 72 else 73 { 74 alert("XDR doesn't exist"); 75 } 76 } 77 </script> 78 </body> 79 </html>
以上就是我在實際項目中遇到的跨域請求資源的情況,有一種跨域需要特別注意就是在https協議下發送https請求,除了使用proxy代理外其他方法都無解,會被瀏覽器直接block掉。如果哪位道友知道解決方法,麻煩你告訴我一聲。
最后附上完整的測試demo
iss中:

1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"> 6 <title>jsonp_test</title> 7 8 <script> 9 /*var f = function(data){ 10 alert(data.name); 11 }*/ 12 var xhr = new XMLHttpRequest(); 13 xhr.onload = function(){ 14 alert(xhr.responseText); 15 }; 16 xhr.open('POST', 'http://localhost:8888/cors', true); 17 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 18 xhr.setRequestHeader("aaaa","b"); 19 xhr.send("f=json"); 20 </script> 21 22 <script> 23 /* var _script = document.createElement('script'); 24 _script.type = "text/javascript"; 25 _script.src = "http://localhost:8888/jsonp?callback=f"; 26 document.head.appendChild(_script);*/ 27 </script> 28 </head> 29 30 <body> 31 </body> 32 </html>
node-html

1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"> 6 <title>proxy_test</title> 7 8 <script> 9 var f = function(data){ 10 alert(data.name); 11 } 12 var xhr = new XMLHttpRequest(); 13 xhr.onload = function(){ 14 alert(xhr.responseText); 15 }; 16 xhr.open('POST', 'http://localhost:8888/proxy?https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer', true); 17 xhr.send("f=json"); 18 </script> 19 </head> 20 21 <body> 22 </body> 23 </html>
node-server

1 var http = require('http'); 2 var url = require('url'); 3 var fs = require('fs'); 4 var qs = require('querystring'); 5 var request = require('request'); 6 7 http.createServer(function(req, res){ 8 var _url = url.parse(req.url); 9 if (_url.pathname === '/jsonp') { 10 var query = _url.query; 11 console.log(query); 12 var params = qs.parse(query); 13 console.log(params); 14 var f = ""; 15 16 f = params.callback; 17 18 res.writeHead(200, {"Content-Type": "text/javascript"}); 19 res.write(f + "({name:'hello world'})"); 20 res.end(); 21 } else if (_url.pathname === '/proxy') { 22 var proxyUrl = ""; 23 if (req.url.indexOf('?') > -1) { 24 proxyUrl = req.url.substr(req.url.indexOf('?') + 1); 25 console.log(proxyUrl); 26 } 27 if (req.method === 'GET') { 28 request.get(proxyUrl).pipe(res); 29 } else if (req.method === 'POST') { 30 var post = ''; //定義了一個post變量,用於暫存請求體的信息 31 32 req.on('data', function(chunk){ //通過req的data事件監聽函數,每當接受到請求體的數據,就累加到post變量中 33 post += chunk; 34 }); 35 36 req.on('end', function(){ //在end事件觸發后,通過querystring.parse將post解析為真正的POST請求格式,然后向客戶端返回。 37 post = qs.parse(post); 38 request({ 39 method: 'POST', 40 url: proxyUrl, 41 form: post 42 }).pipe(res); 43 }); 44 } 45 } else if (_url.pathname === '/index') { 46 fs.readFile('./index.html', function(err, data) { 47 res.writeHead(200, {"Content-Type": "text/html; charset=UTF-8"}); 48 res.write(data); 49 res.end(); 50 }); 51 } else if (_url.pathname === '/cors') { 52 if (req.headers.origin) { 53 54 res.writeHead(200, { 55 "Content-Type": "text/html; charset=UTF-8", 56 "Access-Control-Allow-Origin":'http://localhost', 57 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS', 58 'Access-Control-Allow-Headers': 'X-Requested-With, Content-Type,aaaa'/**/ 59 }); 60 res.write('cors'); 61 res.end(); 62 } 63 } 64 65 }).listen(8888);
參考文獻:
XDomainRequest - Restrictions, Limitations and Workarounds
