同源策略
端口相同
域名相同
協議相同
例子:http://www.example.com/dir/page.html
這個網址,協議是http
,域名是www.example.com
,端口是80
同源政策的目的,是為了保證用戶信息的安全,防止惡意的網站竊取數據。是瀏覽器做的努力
舉個例子:用戶在A網站登錄用戶,在網站上存儲了用戶的個人信息,cookies等等,這時候用戶用同一個瀏覽器新建了一個標簽頁打開了B網站,而B網站上做了一個操作是獲取當前登錄用戶的用戶信息以及cookies等,并利用A網站里的接口發送請求。
用戶在A站點登錄之后,又打開了B站點,但是用戶沒有進行其他操作,而在B站點中,站點B獲取了用戶的數據,并且調用A站點中的方法,自動做相關操作,如進行轉賬,此時,若系統不進行區別請求是從哪里發來的,只要請求被訪問,就做相應操作,那么很輕松的B站點就對用戶U的賬戶進行了轉賬操作,而用戶不知情。
瀏覽器本身做了同源的校驗,只要不符合瀏覽器的同源規則,那么默認不是同源站點,不同源的站點之間不能輕易進行相互獲取資源,除非某一站點進行了授權,方可使本不同源的站點同源。
同源策略限制范圍
Cookie、LocalStorage 、sessionStorage和 IndexDB 無法讀取
DOM 無法獲得
AJAX 請求不能發送
跨域通信的方式
JSONP
CORS
Hash
postMessage
WebSoket
一、CORS跨域資源請求
CORS(Cross-origin resource sharing)跨域資源請求
瀏覽器在請求一個跨域資源的時候,如果是跨域的Ajax請求,他會在請求頭中加一個origin
字段,但他是不知道這個資源服務端是否允許跨域請求的。瀏覽器會發送到服務端,如果服務器返回的頭中沒有'Access-Control-Allow-Origin': '對應網址或 * '
的話,那么瀏覽器就會把請求內容給忽略掉,并且在控制臺報錯
CORS限制
允許的請求方法
GET
POST
HEAD 只請求頁面的首部
允許的Content-Type
text/plain
multipart/form-data
application/x-www-form-ulencoded
其他類型的請求方法和Content-Type需要通過預請求驗證后然后才能發送
?
?
Content-Type屬性用于指定http請求和響應的內容類型,默認為text/html
application/x-www-form-urlencoded
是常用的表單發包方式,普通的表單提交,或者js發包,默認都是通過這種方式,multipart/form-data
用在發送文件的POST包。-
application/json 通過json格式
http通信中不存在所謂的json,而是將string轉成json罷了
CORS預請求
跨域資源共享標準新增了一組 HTTP 首部字段,允許服務器聲明哪些源站有權限訪問哪些資源。另外,規范要求,對那些可能對服務器數據產生副作用的 HTTP 請求方法(特別是 GET 以外的 HTTP 請求,或者搭配某些 MIME 類型的 POST 請求),瀏覽器必須首先使用 OPTIONS 方法發起一個預檢請求。
服務器在HTTP header中加入允許請求的方法和Content-Type后,其他指定的方法和Content-Type就可以成功請求了
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="" cid="n73" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">'Access-Control-Allow-Headers': '允許Content-Type'
'Access-Control-Allow-Methods': '允許的請求方法'
'Access-Control-Max-Age': '預請求允許其他方法和類型傳輸的時間'</pre>
詳解:http://www.ruanyifeng.com/blog/2016/04/cors.html
二、JSONP跨域
瀏覽器上雖然有同源限制,但是像 srcipt標簽、link標簽、img標簽、iframe標簽,這種在標簽上通過src地址來加載一些內容的時候瀏覽器是允許進行跨域請求的。
所以JSONP的原理就是:
創建一個script標簽,這個script標簽的src就是請求的地址;
這個script標簽插入到DOM中,瀏覽器就根據src地址訪問服務器資源
返回的資源是一個文本,但是因為是在script標簽中,瀏覽器會執行它
而這個文本恰好是函數調用的形式,即函數名(數據),瀏覽器會把它當作JS代碼來執行即調用這個函數
只要提前約定好這個函數名,并且這個函數存在于window對象中,就可以把數據傳遞給處理函數。
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n89" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">//前端代碼
function jsonp(req){
var script = document.createElement('script');
//關鍵點就是拼接url
var url = req.url + '?callback=' + req.callback.name;
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
function hello(res){
alert('hello ' + res.data);
}
jsonp({
url : '',
callback : hello
});</pre>
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="javascript" cid="n91" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">//服務端代碼
var http = require('http');
var urllib = require('url');
?
var port = 8080;
var data = {'data':'world'};
?
http.createServer(function(req,res){
var params = urllib.parse(req.url,true);
if(params.query.callback){
console.log(params.query.callback);
//jsonp
var str = params.query.callback + '(' + JSON.stringify(data) + ')';
res.end(str);
} else {
res.end();
}
}).listen(port,function(){
console.log('jsonp server is on');
});</pre>
三、Hash值跨域通信
背景:在頁面A下提供iframe或frame嵌入了跨域的頁面B
容器頁面 -> 嵌入頁通信:
在A頁面中改變B的url中的hash值,B不會刷新,但是B可以用過window.onhashchange
事件監聽到hash變化
四、postMessage通信
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" cid="n100" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">// 窗口A中
window.postMessage('data', 'http://A.com');
// 窗口B中
window.addEventListener('message', function(event) {
console.log(event.origin); // http://A.com
console.log(event.source); // A 對象window引用
console.log(event.data); // 數據
})</pre>
五、WebSoket 跨域通信
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" cid="n102" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">var ws = new WebSocket('wss://echo.websoket.org') //這個是后端端口
?
ws.onopen = function(evt) {
ws.send('some message')
}
?
ws.onmessage = function (evt) {
console.log(evt.data);
}
?
ws.onclose = function(evt){
console.log('連接關閉');
}</pre>
六、document.domain
該方式只能用于二級域名相同的情況下,比如 a.test.com 和 b.test.com 適用于該方式。
只需要給頁面添加 document.domain = 'test.com' 表示二級域名都相同就可以實現跨域