同源策略
端口相同
域名相同
協(xié)議相同
例子:http://www.example.com/dir/page.html
這個(gè)網(wǎng)址豺瘤,協(xié)議是http
,域名是www.example.com
听诸,端口是80
同源政策的目的坐求,是為了保證用戶信息的安全,防止惡意的網(wǎng)站竊取數(shù)據(jù)晌梨。是瀏覽器做的努力
舉個(gè)例子:用戶在A網(wǎng)站登錄用戶桥嗤,在網(wǎng)站上存儲(chǔ)了用戶的個(gè)人信息,cookies等等仔蝌,這時(shí)候用戶用同一個(gè)瀏覽器新建了一個(gè)標(biāo)簽頁(yè)打開了B網(wǎng)站泛领,而B網(wǎng)站上做了一個(gè)操作是獲取當(dāng)前登錄用戶的用戶信息以及cookies等,并利用A網(wǎng)站里的接口發(fā)送請(qǐng)求敛惊。
用戶在A站點(diǎn)登錄之后渊鞋,又打開了B站點(diǎn),但是用戶沒(méi)有進(jìn)行其他操作,而在B站點(diǎn)中锡宋,站點(diǎn)B獲取了用戶的數(shù)據(jù)儡湾,并且調(diào)用A站點(diǎn)中的方法,自動(dòng)做相關(guān)操作执俩,如進(jìn)行轉(zhuǎn)賬盒粮,此時(shí),若系統(tǒng)不進(jìn)行區(qū)別請(qǐng)求是從哪里發(fā)來(lái)的奠滑,只要請(qǐng)求被訪問(wèn),就做相應(yīng)操作妒穴,那么很輕松的B站點(diǎn)就對(duì)用戶U的賬戶進(jìn)行了轉(zhuǎn)賬操作宋税,而用戶不知情。
瀏覽器本身做了同源的校驗(yàn)讼油,只要不符合瀏覽器的同源規(guī)則杰赛,那么默認(rèn)不是同源站點(diǎn),不同源的站點(diǎn)之間不能輕易進(jìn)行相互獲取資源矮台,除非某一站點(diǎn)進(jìn)行了授權(quán)乏屯,方可使本不同源的站點(diǎn)同源。
同源策略限制范圍
Cookie瘦赫、LocalStorage 辰晕、sessionStorage和 IndexDB 無(wú)法讀取
DOM 無(wú)法獲得
AJAX 請(qǐng)求不能發(fā)送
跨域通信的方式
JSONP
CORS
Hash
postMessage
WebSoket
一、CORS跨域資源請(qǐng)求
CORS(Cross-origin resource sharing)跨域資源請(qǐng)求
瀏覽器在請(qǐng)求一個(gè)跨域資源的時(shí)候确虱,如果是跨域的Ajax請(qǐng)求含友,他會(huì)在請(qǐng)求頭中加一個(gè)origin
字段,但他是不知道這個(gè)資源服務(wù)端是否允許跨域請(qǐng)求的校辩。瀏覽器會(huì)發(fā)送到服務(wù)端窘问,如果服務(wù)器返回的頭中沒(méi)有'Access-Control-Allow-Origin': '對(duì)應(yīng)網(wǎng)址或 * '
的話,那么瀏覽器就會(huì)把請(qǐng)求內(nèi)容給忽略掉宜咒,并且在控制臺(tái)報(bào)錯(cuò)
CORS限制
允許的請(qǐng)求方法
GET
POST
HEAD 只請(qǐng)求頁(yè)面的首部
允許的Content-Type
text/plain
multipart/form-data
application/x-www-form-ulencoded
其他類型的請(qǐng)求方法和Content-Type需要通過(guò)預(yù)請(qǐng)求驗(yàn)證后然后才能發(fā)送
?
?
Content-Type屬性用于指定http請(qǐng)求和響應(yīng)的內(nèi)容類型惠赫,默認(rèn)為text/html
application/x-www-form-urlencoded
是常用的表單發(fā)包方式,普通的表單提交故黑,或者js發(fā)包儿咱,默認(rèn)都是通過(guò)這種方式,multipart/form-data
用在發(fā)送文件的POST包场晶。-
application/json 通過(guò)json格式
http通信中不存在所謂的json概疆,而是將string轉(zhuǎn)成json罷了
CORS預(yù)請(qǐng)求
跨域資源共享標(biāo)準(zhǔn)新增了一組 HTTP 首部字段,允許服務(wù)器聲明哪些源站有權(quán)限訪問(wèn)哪些資源峰搪。另外岔冀,規(guī)范要求,對(duì)那些可能對(duì)服務(wù)器數(shù)據(jù)產(chǎn)生副作用的 HTTP 請(qǐng)求方法(特別是 GET 以外的 HTTP 請(qǐng)求,或者搭配某些 MIME 類型的 POST 請(qǐng)求)使套,瀏覽器必須首先使用 OPTIONS 方法發(fā)起一個(gè)預(yù)檢請(qǐng)求罐呼。
服務(wù)器在HTTP header中加入允許請(qǐng)求的方法和Content-Type后,其他指定的方法和Content-Type就可以成功請(qǐng)求了
<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': '允許的請(qǐng)求方法'
'Access-Control-Max-Age': '預(yù)請(qǐng)求允許其他方法和類型傳輸?shù)臅r(shí)間'</pre>
詳解:http://www.ruanyifeng.com/blog/2016/04/cors.html
二侦高、JSONP跨域
瀏覽器上雖然有同源限制嫉柴,但是像 srcipt標(biāo)簽、link標(biāo)簽奉呛、img標(biāo)簽计螺、iframe標(biāo)簽,這種在標(biāo)簽上通過(guò)src地址來(lái)加載一些內(nèi)容的時(shí)候?yàn)g覽器是允許進(jìn)行跨域請(qǐng)求的瞧壮。
所以JSONP的原理就是:
創(chuàng)建一個(gè)script標(biāo)簽登馒,這個(gè)script標(biāo)簽的src就是請(qǐng)求的地址;
這個(gè)script標(biāo)簽插入到DOM中咆槽,瀏覽器就根據(jù)src地址訪問(wèn)服務(wù)器資源
返回的資源是一個(gè)文本陈轿,但是因?yàn)槭窃趕cript標(biāo)簽中,瀏覽器會(huì)執(zhí)行它
而這個(gè)文本恰好是函數(shù)調(diào)用的形式秦忿,即函數(shù)名(數(shù)據(jù))麦射,瀏覽器會(huì)把它當(dāng)作JS代碼來(lái)執(zhí)行即調(diào)用這個(gè)函數(shù)
只要提前約定好這個(gè)函數(shù)名,并且這個(gè)函數(shù)存在于window對(duì)象中灯谣,就可以把數(shù)據(jù)傳遞給處理函數(shù)潜秋。
<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');
//關(guān)鍵點(diǎn)就是拼接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;">//服務(wù)端代碼
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值跨域通信
背景:在頁(yè)面A下提供iframe或frame嵌入了跨域的頁(yè)面B
容器頁(yè)面 -> 嵌入頁(yè)通信:
在A頁(yè)面中改變B的url中的hash值胎许,B不會(huì)刷新半等,但是B可以用過(guò)window.onhashchange
事件監(jiān)聽到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 對(duì)象window引用
console.log(event.data); // 數(shù)據(jù)
})</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') //這個(gè)是后端端口
?
ws.onopen = function(evt) {
ws.send('some message')
}
?
ws.onmessage = function (evt) {
console.log(evt.data);
}
?
ws.onclose = function(evt){
console.log('連接關(guān)閉');
}</pre>
六杀饵、document.domain
該方式只能用于二級(jí)域名相同的情況下,比如 a.test.com 和 b.test.com 適用于該方式谬擦。
只需要給頁(yè)面添加 document.domain = 'test.com' 表示二級(jí)域名都相同就可以實(shí)現(xiàn)跨域