六種跨域解決方案

同源策略

  • 端口相同

  • 域名相同

  • 協(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)跨域

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末切距,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子惨远,更是在濱河造成了極大的恐慌谜悟,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件北秽,死亡現(xiàn)場(chǎng)離奇詭異葡幸,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)贺氓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門蔚叨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事蔑水⌒暇猓” “怎么了?”我有些...
    開封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵搀别,是天一觀的道長(zhǎng)丹擎。 經(jīng)常有香客問(wèn)我,道長(zhǎng)歇父,這世上最難降的妖魔是什么蒂培? 我笑而不...
    開封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮榜苫,結(jié)果婚禮上护戳,老公的妹妹穿的比我還像新娘。我一直安慰自己单刁,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開白布府适。 她就那樣靜靜地躺著羔飞,像睡著了一般。 火紅的嫁衣襯著肌膚如雪檐春。 梳的紋絲不亂的頭發(fā)上逻淌,一...
    開封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音疟暖,去河邊找鬼卡儒。 笑死,一個(gè)胖子當(dāng)著我的面吹牛俐巴,可吹牛的內(nèi)容都是我干的骨望。 我是一名探鬼主播,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼欣舵,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼擎鸠!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起缘圈,我...
    開封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤瓮栗,失蹤者是張志新(化名)和其女友劉穎吴藻,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡以蕴,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了洒宝。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片扶镀。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出滞项,到底是詐尸還是另有隱情狭归,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布文判,位于F島的核電站过椎,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏戏仓。R本人自食惡果不足惜疚宇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望赏殃。 院中可真熱鬧敷待,春花似錦、人聲如沸仁热。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)抗蠢。三九已至举哟,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間迅矛,已是汗流浹背妨猩。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留秽褒,地道東北人壶硅。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像销斟,于是被迫代替她去往敵國(guó)和親庐椒。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 什么是跨域 跨域蚂踊,是指瀏覽器不能執(zhí)行其他網(wǎng)站的腳本扼睬。它是由瀏覽器的同源策略造成的,是瀏覽器對(duì)JavaScript實(shí)...
    他方l閱讀 1,064評(píng)論 0 2
  • 什么是跨域 跨域悴势,是指瀏覽器不能執(zhí)行其他網(wǎng)站的腳本窗宇。它是由瀏覽器的同源策略造成的,是瀏覽器對(duì)JavaScript實(shí)...
    Yaoxue9閱讀 1,299評(píng)論 0 6
  • 題目1.什么是同源策略? 同源策略(Same origin Policy): 瀏覽器出于安全方面的考慮特纤,只允許與本...
    FLYSASA閱讀 1,721評(píng)論 0 6
  • 什么是跨域 跨域军俊,是指瀏覽器不能執(zhí)行其他網(wǎng)站的腳本。它是由瀏覽器的同源策略造成的捧存,是瀏覽器對(duì)JavaScript實(shí)...
    HeroXin閱讀 836評(píng)論 0 4
  • 1. 什么是同源策略 瀏覽器限制不同源的兩個(gè)網(wǎng)站間腳本和文本的相互訪問(wèn)粪躬,只允許訪問(wèn)同源下的內(nèi)容担败。所謂同源,就是指兩...
    熊蛋子17閱讀 686評(píng)論 1 6