六種跨域解決方案

同源策略

  • 端口相同

  • 域名相同

  • 協議相同

例子: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' 表示二級域名都相同就可以實現跨域

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,702評論 6 534
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,615評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,606評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,044評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,826評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,227評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,307評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,447評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,992評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,807評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,001評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,550評論 5 361
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,243評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,667評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,930評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,709評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,996評論 2 374

推薦閱讀更多精彩內容

  • 什么是跨域 跨域,是指瀏覽器不能執行其他網站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對JavaScript實...
    他方l閱讀 1,071評論 0 2
  • 什么是跨域 跨域,是指瀏覽器不能執行其他網站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對JavaScript實...
    Yaoxue9閱讀 1,311評論 0 6
  • 題目1.什么是同源策略? 同源策略(Same origin Policy): 瀏覽器出于安全方面的考慮,只允許與本...
    FLYSASA閱讀 1,741評論 0 6
  • 什么是跨域 跨域,是指瀏覽器不能執行其他網站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對JavaScript實...
    HeroXin閱讀 845評論 0 4
  • 1. 什么是同源策略 瀏覽器限制不同源的兩個網站間腳本和文本的相互訪問,只允許訪問同源下的內容。所謂同源,就是指兩...
    熊蛋子17閱讀 695評論 1 6