跨域就是實(shí)現(xiàn)不同域的接口進(jìn)行數(shù)據(jù)交互吁断。
一天试、jsonp
html中script標(biāo)簽可以引入其他域下的js槐壳,比如引入線上的jquery庫(kù)。利用這個(gè)特性喜每,可實(shí)現(xiàn)跨域訪問(wèn)接口务唐,不過(guò)需要后端支持。
web頁(yè)面中带兜,通過(guò)script標(biāo)簽獲取js代碼可以進(jìn)行跨域枫笛,我們可以動(dòng)態(tài)的創(chuàng)建script標(biāo)簽,設(shè)置src屬性指向我們請(qǐng)求資源的url地址刚照,然后放到head標(biāo)簽中刑巧。這樣就可以把不同域的數(shù)據(jù)加載到本域名下,不過(guò)需要后端支持jsonp无畔,也就是通過(guò)前端的url中的callback參數(shù)動(dòng)態(tài)的生成回調(diào)函數(shù)名啊楚,通過(guò)傳參的形式執(zhí)行獲取到的數(shù)據(jù),這樣的話浑彰,前端預(yù)定義好的函數(shù)就可以讓傳來(lái)的數(shù)據(jù)自動(dòng)運(yùn)行恭理。
介紹跨域方式之前,我們先來(lái)修改本機(jī)的hosts文件如下:
127.0.0.1 localhost
127.0.0.1 test.com
127.0.0.1 a.test.com
127.0.0.1 b.test.com
這樣本地地址就對(duì)應(yīng)了不同的域闸昨。
JSONP的跨域方式是利用<script>
標(biāo)簽的src屬性可以跨域引用資源的特點(diǎn)蚯斯,有這些屬性的標(biāo)簽還有<img>
、<iframe>
饵较,但是JSONP只支持get方式拍嵌。
下面以點(diǎn)擊獲取隨機(jī)新聞列表的例子來(lái)演示一下JSONP的具體工作原理(test.com訪問(wèn)a.test.com)
HTML:
<div class="container">
<ul class="news">
<li>第11日前瞻:中國(guó)沖擊4金 博爾特再戰(zhàn)</li>
<li>男雙力爭(zhēng)會(huì)師決賽 </li>
<li>女排將死磕巴西!</li>
</ul>
<button class="change">換一組</button>
</div>
首先循诉,在前端横辆,我們要在調(diào)用資源的時(shí)候動(dòng)態(tài)創(chuàng)建script標(biāo)簽,并設(shè)置src屬性指向資源的URL地址茄猫,代碼如下:
document.querySelector('.change').addEventListener('click', function() {
var script = document.createElement('script')
script.setAttribute('src', '//a.test.com:8080/getNews?callback=appendHtml') //callback=appendHtml是給后端資源打包數(shù)據(jù)用的參數(shù)狈蚤,同時(shí)也是前端定義的回調(diào)函數(shù)
document.head.appendChild(script)
document.head.removeChild(script) //刪除script標(biāo)簽是因?yàn)閟cript標(biāo)簽插入頁(yè)面的時(shí)候資源已經(jīng)請(qǐng)求到了
})
定義獲取資源后需要執(zhí)行的回調(diào)函數(shù):
function appendHtml(news) {
var html = ''
for (var i = 0; i < news.length; i++) {
html += '<li>' + news[i] + '</li>'
}
document.querySelector('.news').innerHTML = html
}
后端是把前端發(fā)送的URL地址拿到的數(shù)據(jù)以前端定義的回調(diào)函數(shù)(appendHtml)的參數(shù)的形式返回給前端,這樣到了前端就可以調(diào)用執(zhí)行了:
var news = [
"第11日前瞻:中國(guó)沖擊4金 博爾特再戰(zhàn)200米羽球",
"正直播柴飚/洪煒出戰(zhàn) 男雙力爭(zhēng)會(huì)師決賽",
"女排將死磕巴西划纽!郎平安排男陪練模仿對(duì)方核心",
"沒(méi)有中國(guó)選手和巨星的110米欄 我們還看嗎脆侮?",
"中英上演奧運(yùn)金牌大戰(zhàn)",
"博彩賠率挺中國(guó)奪回第二紐約時(shí)報(bào):中國(guó)因?qū)κ址幎鴣G失的獎(jiǎng)牌最多",
"最“出柜”奧運(yùn)?同性之愛(ài)閃耀里約",
"下跪拜謝與洪荒之力一樣 都是真情流露"
]
var data = [];
for (var i = 0; i < 3; i++) {
var index = Math.floor(Math.random() * news.length);
data.push(news[index]);
}
var callback = req.query.callback; //查詢前端有沒(méi)有傳入回調(diào)函數(shù)
if (callback) {
res.send(callback + '(' + JSON.stringify(data) + ')'); //數(shù)據(jù)以函數(shù)參數(shù)的方式傳給前端
} else {
res.send(data);
}
這樣我們就從test.com訪問(wèn)到了a.test.com下的資源勇劣。
二靖避、cors
CORS 全稱是跨域資源共享(Cross-Origin Resource Sharing)潭枣,是一種 ajax 跨域請(qǐng)求資源的方式,支持現(xiàn)代瀏覽器幻捏,IE支持10以上盆犁。 實(shí)現(xiàn)方式很簡(jiǎn)單,當(dāng)你使用 XMLHttpRequest 發(fā)送請(qǐng)求時(shí)篡九,瀏覽器發(fā)現(xiàn)該請(qǐng)求不符合同源策略谐岁,會(huì)給該請(qǐng)求加一個(gè)請(qǐng)求頭:Origin,后臺(tái)進(jìn)行一系列處理榛臼,如果確定接受請(qǐng)求則在返回結(jié)果中加入一個(gè)響應(yīng)頭:Access-Control-Allow-Origin伊佃。 瀏覽器判斷該響應(yīng)頭中是否包含 Origin 的值,如果有則瀏覽器會(huì)處理響應(yīng)讽坏,我們就可以拿到響應(yīng)數(shù)據(jù)锭魔,如果不包含瀏覽器直接駁回例证,這時(shí)我們無(wú)法拿到響應(yīng)數(shù)據(jù)路呜。所以 CORS 的表象是讓你覺(jué)得它與同源的 ajax 請(qǐng)求沒(méi)啥區(qū)別,代碼完全一樣 织咧。
同樣以上面的列子來(lái)演示胀葱。首先JS部分,發(fā)起AJAX請(qǐng)求(與同域相同):
document.querySelector('.change').addEventListener('click', function () {
var xhr = new XMLHttpRequest();
xhr.open('get', '//a.test.com:8080/getNews', true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
appendHtml(JSON.parse(xhr.responseText))
}
}
window.xhr = xhr
})
function appendHtml(news) {
var html = ''
for (var i = 0; i < news.length; i++) {
html += '<li>' + news[i] + '</li>'
}
document.querySelector('.news').innerHTML = html
}
后端在向前端發(fā)送資源之前笙蒙,設(shè)置請(qǐng)求頭 "Access-Control-Allow-Origin":
var news = [
"第11日前瞻:中國(guó)沖擊4金 博爾特再戰(zhàn)200米羽球",
"正直播柴飚/洪煒出戰(zhàn) 男雙力爭(zhēng)會(huì)師決賽",
"女排將死磕巴西抵屿!郎平安排男陪練模仿對(duì)方核心",
"沒(méi)有中國(guó)選手和巨星的110米欄 我們還看嗎?",
"中英上演奧運(yùn)金牌大戰(zhàn)",
"博彩賠率挺中國(guó)奪回第二紐約時(shí)報(bào):中國(guó)因?qū)κ址幎鴣G失的獎(jiǎng)牌最多",
"最“出柜”奧運(yùn)捅位?同性之愛(ài)閃耀里約",
"下跪拜謝與洪荒之力一樣 都是真情流露"
]
var data = [];
for (var i = 0; i < 3; i++) {
var index = Math.floor(Math.random() * news.length);
data.push(news[index]);
}
res.header("Access-Control-Allow-Origin", "http://test.com:8080"); // "http://test.com:8080"表示只有“test.com:8080”域下發(fā)起的請(qǐng)求才可以調(diào)用本域下的資源
//res.header("Access-Control-Allow-Origin", "*"); //"*"表示任何域下發(fā)起請(qǐng)求都可以調(diào)用本域下的資源
res.send(data);
三轧葛、降域
降域是相對(duì)于iframe元素而言的 。
比如艇搀,域名為http://b.baidu.com/b (A)的網(wǎng)頁(yè)以iframe的形式嵌在域名為http://a.baidu.com/a (B)的網(wǎng)頁(yè)中尿扯,正常情況下,該請(qǐng)求不符合瀏覽器的同源策略焰雕,不能進(jìn)行跨域訪問(wèn)衷笋。但是當(dāng)我們?cè)趦蓚€(gè)頁(yè)面中分別設(shè)置documet.domain = baidu.com的時(shí)候(注意:這個(gè)方法有一個(gè)限制就是域名中必須有相同的部分),B頁(yè)面就可以訪問(wèn)到A頁(yè)面中的資源了矩屁。比如下面的代碼:
B頁(yè)面:
<html>
<style>
html,
body {
margin: 0;
}
input {
margin: 20px;
width: 200px;
}
</style>
<input id="input" type="text" placeholder="http://b.test.com/b.html">
<script>
// URL: http://b.test.com/b.html
document.querySelector('#input').addEventListener('input', function () {
window.parent.document.querySelector('input').value = this.value;
})
document.domain = 'test.com';
</script>
</html>
A頁(yè)面:
<html>
<style>
.ct {
width: 910px;
margin: auto;
}
.main {
float: left;
width: 450px;
height: 300px;
border: 1px solid #ccc;
}
.main input {
margin: 20px;
width: 200px;
}
.iframe {
float: right;
}
iframe {
width: 450px;
height: 300px;
border: 1px dashed #ccc;
}
</style>
<div class="ct">
<h1>使用降域?qū)崿F(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.test.com:8080/a.html">
</div>
<iframe src="http://b.test.com:8080/b.html" frameborder="0"></iframe>
</div>
<script>
//URL: http://a.test.com:8080/a.html
document.querySelector('.main input').addEventListener('input', function () {
console.log(this.value);
window.frames[0].document.querySelector('input').value = this.value;
})
document.domain = "test.com"
</script>
</html>
通過(guò)a.test.com/a.html訪問(wèn)b.test.com/b.html辟宗,實(shí)現(xiàn)了跨域訪問(wèn),效果如下:
四吝秕、postMessage
window.postMessage()是HTML5的新方法泊脐,IE8+支持∷盖停可以使用它來(lái)向其它的window對(duì)象發(fā)送數(shù)據(jù)容客,無(wú)論這個(gè)window對(duì)象是屬于同源或不同源。
postMessage(data, origin)方法接收兩個(gè)參數(shù):
- data:要傳遞的數(shù)據(jù)。html5規(guī)范中提到該參數(shù)可以是JavaScript的任意基本類(lèi)型或可復(fù)制的對(duì)象耘柱,然而并不是所有瀏覽器都做到了這點(diǎn)如捅,部分瀏覽器只能處理字符串參數(shù),所以我們?cè)趥鬟f參數(shù)的時(shí)候需要使用JSON.stringify()方法對(duì)對(duì)象參數(shù)序列化调煎,在低版本IE中引用json2.js可以實(shí)現(xiàn)類(lèi)似效果镜遣。
- origin: 字符串參數(shù)。用來(lái)限定接收消息的那個(gè)window對(duì)象所在的域士袄,如果不想限定域悲关,可以使用通配符
*
,這樣可以傳遞給任意窗口娄柳,如果要指定和當(dāng)前窗口同源的話設(shè)置為"/"寓辱。
同樣以上面的例子來(lái)說(shuō)明postMessage()的原理(A頁(yè)面中嵌套了一個(gè)B頁(yè)面)
那么我們可以在A頁(yè)面中通過(guò)postMessage()方法向跨域的B頁(yè)面?zhèn)鬟f數(shù)據(jù)
<html>
<style>
.ct {
width: 910px;
margin: auto;
}
.main {
float: left;
width: 450px;
height: 300px;
border: 1px solid #ccc;
}
.main input {
margin: 20px;
width: 200px;
}
.iframe {
float: right;
}
iframe {
width: 450px;
height: 300px;
border: 1px dashed #ccc;
}
</style>
<div class="ct">
<h1>使用降域?qū)崿F(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.test.com:8080/a.html">
</div>
<iframe src="http://b.test.com:8080/b.html" frameborder="0"></iframe>
</div>
<script>
document.querySelector('.main input').addEventListener('input', function () {
window.frames[0].postMessage(this.value, '*')
})
window.addEventListener('message', function (e) {
document.querySelector('input').value = e.data
})
</script>
</html>
那么,我們?cè)趺丛贐頁(yè)面上接收A頁(yè)面?zhèn)鬟f過(guò)來(lái)的數(shù)據(jù)呢赤拒,我們只要在B頁(yè)面監(jiān)聽(tīng)window的message事件就可以秫筏,消息內(nèi)容儲(chǔ)存在該事件對(duì)象的data屬性中。
<html>
<input id="input" type="text" placeholder="http://b.test.com/b.html">
<script>
document.querySelector('input').addEventListener('input', function () {
window.parent.postMessage(this.value, '*')
})
window.addEventListener('message', function (e) {
document.querySelector('input').value = e.data
})
</script>
</html>
同樣挎挖,如果想要在B頁(yè)面發(fā)送數(shù)據(jù)这敬,A頁(yè)面接受數(shù)據(jù),只要在B頁(yè)面使用postMessage()方法蕉朵,然后在A頁(yè)面監(jiān)聽(tīng)window的message事件即可崔涂。
最終頁(yè)面得到的效果如下:
參考