六種跨域解決方案

同源策略

  • 端口相同

  • 域名相同

  • 協(xié)議相同

例子:http://www.example.com/dir/page.html 這個網(wǎng)址,協(xié)議是http,域名是www.example.com,端口是80

同源政策的目的,是為了保證用戶信息的安全,防止惡意的網(wǎng)站竊取數(shù)據(jù)。是瀏覽器做的努力

舉個例子:用戶在A網(wǎng)站登錄用戶,在網(wǎng)站上存儲了用戶的個人信息,cookies等等,這時候用戶用同一個瀏覽器新建了一個標簽頁打開了B網(wǎng)站,而B網(wǎng)站上做了一個操作是獲取當前登錄用戶的用戶信息以及cookies等,并利用A網(wǎng)站里的接口發(fā)送請求。

用戶在A站點登錄之后,又打開了B站點,但是用戶沒有進行其他操作,而在B站點中,站點B獲取了用戶的數(shù)據(jù),并且調用A站點中的方法,自動做相關操作,如進行轉賬,此時,若系統(tǒng)不進行區(qū)別請求是從哪里發(fā)來的,只要請求被訪問,就做相應操作,那么很輕松的B站點就對用戶U的賬戶進行了轉賬操作,而用戶不知情。

瀏覽器本身做了同源的校驗,只要不符合瀏覽器的同源規(guī)則,那么默認不是同源站點,不同源的站點之間不能輕易進行相互獲取資源,除非某一站點進行了授權,方可使本不同源的站點同源。

同源策略限制范圍

  • Cookie、LocalStorage 、sessionStorage和 IndexDB 無法讀取

  • DOM 無法獲得

  • AJAX 請求不能發(fā)送

跨域通信的方式

  • JSONP

  • CORS

  • Hash

  • postMessage

  • WebSoket

一、CORS跨域資源請求

CORS(Cross-origin resource sharing)跨域資源請求

瀏覽器在請求一個跨域資源的時候,如果是跨域的Ajax請求,他會在請求頭中加一個origin字段,但他是不知道這個資源服務端是否允許跨域請求的。瀏覽器會發(fā)送到服務端,如果服務器返回的頭中沒有'Access-Control-Allow-Origin': '對應網(wǎng)址或 * ' 的話,那么瀏覽器就會把請求內容給忽略掉,并且在控制臺報錯

CORS限制

允許的請求方法

  • GET

  • POST

  • HEAD 只請求頁面的首部

允許的Content-Type

  • text/plain

  • multipart/form-data

  • application/x-www-form-ulencoded

其他類型的請求方法和Content-Type需要通過預請求驗證后然后才能發(fā)送

?


?

Content-Type屬性用于指定http請求和響應的內容類型,默認為text/html

  • application/x-www-form-urlencoded是常用的表單發(fā)包方式,普通的表單提交,或者js發(fā)包,默認都是通過這種方式,

  • multipart/form-data用在發(fā)送文件的POST包。

  • application/json 通過json格式

    http通信中不存在所謂的json,而是將string轉成json罷了

CORS預請求

跨域資源共享標準新增了一組 HTTP 首部字段,允許服務器聲明哪些源站有權限訪問哪些資源。另外,規(guī)范要求,對那些可能對服務器數(shù)據(jù)產生副作用的 HTTP 請求方法(特別是 GET 以外的 HTTP 請求,或者搭配某些 MIME 類型的 POST 請求),瀏覽器必須首先使用 OPTIONS 方法發(fā)起一個預檢請求。

服務器在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': '預請求允許其他方法和類型傳輸?shù)臅r間'</pre>

詳解:http://www.ruanyifeng.com/blog/2016/04/cors.html

二、JSONP跨域

瀏覽器上雖然有同源限制,但是像 srcipt標簽、link標簽、img標簽、iframe標簽,這種在標簽上通過src地址來加載一些內容的時候瀏覽器是允許進行跨域請求的

所以JSONP的原理就是:

  • 創(chuàng)建一個script標簽,這個script標簽的src就是請求的地址;

  • 這個script標簽插入到DOM中,瀏覽器就根據(jù)src地址訪問服務器資源

  • 返回的資源是一個文本,但是因為是在script標簽中,瀏覽器會執(zhí)行它

  • 而這個文本恰好是函數(shù)調用的形式,即函數(shù)名(數(shù)據(jù)),瀏覽器會把它當作JS代碼來執(zhí)行即調用這個函數(shù)

  • 只要提前約定好這個函數(shù)名,并且這個函數(shù)存在于window對象中,就可以把數(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');
//關鍵點就是拼接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事件監(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 對象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') //這個是后端端口
?
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' 表示二級域名都相同就可以實現(xiàn)跨域

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

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

友情鏈接更多精彩內容