處理跨域的主要方法html
本文主要討論CORS解決AJAX由於瀏覽器同源策略不能跨域請求數據的問題。json
JSONP跨域能夠參考下面這篇博客
JSONP跨域跨域
關於CORS細節能夠閱讀跨域資源共享 CORS 詳解。瀏覽器
跨域資源共享 CORS服務器
1. 跨域資源共享CORS(Cross-origin resource sharing)cors
CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。它容許瀏覽器向跨源服務器,發出XMLHttpRequest請求,從而解決了AJAX不能跨域請求的問題。異步
2. CORS須要瀏覽器和服務器同時支持。async
整個CORS通訊過程,都是瀏覽器自動完成,不須要用戶參與。對於開發者來講,CORS通訊與同源的AJAX通訊沒有差異,代碼徹底同樣。瀏覽器一旦發現AJAX請求跨源,就會自動添加一些附加的頭信息,有時還會多出一次附加的請求,但用戶不會有感受。函數
所以,實現CORS通訊的關鍵是服務器。只要服務器實現了CORS接口,就能夠跨源通訊。ui
CORS容許瀏覽器向跨源服務器,發出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。
Ajax即「Asynchronous JavaScript and XML」(異步的JavaScript與XML技術)
Ajax 是一種用於建立快速動態網頁的技術。經過在後臺與服務器進行少許數據交換,Ajax 可使網頁實現異步更新。這意味着能夠在不從新加載整個網頁的狀況下,對網頁的某部分進行更新。
XMLHttpRequest對象是瀏覽器提供的一個API,用來順暢地向服務器發送請求並解析服務器響應,固然整個過程當中,瀏覽器頁面不會被刷新。
1.建立XMLHttpRequest對象var xhr = new XMLHttpRequest();
兼容各個瀏覽器的建立方法
function createRequest (){ try { xhr = new XMLHttpRequest(); }catch (tryMS){ try { xhr = new ActiveXObject("Msxm12.XMLHTTP"); } catch (otherMS) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }catch (failed) { xhr = null; } } } return xhr; }
2.準備請求xhr.open(method,url,async);
3.發送請求xhr.send();
send() 方法的參數能夠是任何你想發送給服務器的內容
4.處理響應
xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ console.log(xhr.responseText); } }
readyState狀態值
代碼實現以下:
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>Document</title> </head> <body> <button id="myButton">點我</button> <script src="./main.js"></script> </body> </html>
JS
myButton=document.getElementById('myButton') myButton.addEventListener('click',(e)=>{ let xhr=new XMLHttpRequest() xhr.onreadystatechange=()=>{ if( xhr.readyState===4){ console.log("請求響應都完畢了") if( xhr.status>=200&& xhr.status<300){ console.log("請求成功") console.log(typeof xhr.responseText)//判斷返回數據的類型是String console.log( xhr.responseText) let string= xhr.responseText let object=window.JSON.parse(string) console.log(typeof object) console.log(object) }else if( xhr.status>=400){ console.log("請求失敗") } } } xhr.open('GET','/xxx') xhr.send() })
if(path==='/xxx'){ response.statusCode=200 response.setHeader('Content-Type', 'text/json;charset=utf-8') response.write(` { "note":{ "to":"xxx", "from":"yyy", "content":"hello" } } `) response.end() }
當發送請求的時候,就會根據xml.open('GET','/xxx')
找到對應的請求路徑。在本文是找到/xxx
路徑,而後返回所請求的數據,在瀏覽器運行結果以下。
CORS跨域
關於CORS細節能夠閱讀跨域資源共享 CORS 詳解。
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>Document</title> </head> <body> <button id="myButton">點我</button> <script src="./main.js"></script> </body> </html>
JS
myButton.addEventListener('click',(e)=>{ let xhr=new XMLHttpRequest() xhr.open('GET','http://jack.com:8002/xxx') xhr.onreadystatechange=()=>{ if(xhr.readyState===4){ console.log("請求響應都完畢了") if(xhr.status>=200&&xhr.status<300){ console.log("請求成功") console.log(typeof xhr.responseText) console.log(xhr.responseText) let string=xhr.responseText let object=window.JSON.parse(string) console.log(typeof object) console.log(object) }else if(xhr.status>=400){ console.log("請求失敗") } } } xhr.send() })
if(path==='/xxx'){ response.statusCode=200 response.setHeader('Content-Type', 'text/json;charset=utf-8') response.setHeader('Access-Control-Allow-Origin','http://blog1.com:8001') response.write(` { "note":{ "to":"xxx", "from":"yyy", "content":"hello" } } `) response.end() }
能夠看到當代碼沒有下面這一行代碼時AJAX並不能跨域請求 response.setHeader('Access-Control-Allow-Origin','http://blog1.com:8001')
的時候,結果以下
從結果能夠看出,由於瀏覽器的同源策略,Ajax不能跨域請求
解決的辦法是添加 response.setHeader('Access-Control-Allow-Origin','http://blog1.com:8001')