跨域就是實現(xiàn)不同域的接口進(jìn)行數(shù)據(jù)交互。
一、jsonp
html中script標(biāo)簽可以引入其他域下的js,比如引入線上的jquery庫。利用這個特性,可實現(xiàn)跨域訪問接口,不過需要后端支持。
web頁面中,通過script標(biāo)簽獲取js代碼可以進(jìn)行跨域,我們可以動態(tài)的創(chuàng)建script標(biāo)簽,設(shè)置src屬性指向我們請求資源的url地址,然后放到head標(biāo)簽中。這樣就可以把不同域的數(shù)據(jù)加載到本域名下,不過需要后端支持jsonp,也就是通過前端的url中的callback參數(shù)動態(tài)的生成回調(diào)函數(shù)名,通過傳參的形式執(zhí)行獲取到的數(shù)據(jù),這樣的話,前端預(yù)定義好的函數(shù)就可以讓傳來的數(shù)據(jù)自動運(yùn)行。
介紹跨域方式之前,我們先來修改本機(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
這樣本地地址就對應(yīng)了不同的域。
JSONP的跨域方式是利用<script>標(biāo)簽的src屬性可以跨域引用資源的特點(diǎn),有這些屬性的標(biāo)簽還有<img>、<iframe>,但是JSONP只支持get方式。
下面以點(diǎn)擊獲取隨機(jī)新聞列表的例子來演示一下JSONP的具體工作原理(test.com訪問a.test.com)
HTML:
<div class="container">
<ul class="news">
<li>第11日前瞻:中國沖擊4金 博爾特再戰(zhàn)</li>
<li>男雙力爭會師決賽 </li>
<li>女排將死磕巴西!</li>
</ul>
<button class="change">換一組</button>
</div>
首先,在前端,我們要在調(diào)用資源的時候動態(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ù),同時也是前端定義的回調(diào)函數(shù)
document.head.appendChild(script)
document.head.removeChild(script) //刪除script標(biāo)簽是因為script標(biāo)簽插入頁面的時候資源已經(jī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日前瞻:中國沖擊4金 博爾特再戰(zhàn)200米羽球",
"正直播柴飚/洪煒出戰(zhàn) 男雙力爭會師決賽",
"女排將死磕巴西!郎平安排男陪練模仿對方核心",
"沒有中國選手和巨星的110米欄 我們還看嗎?",
"中英上演奧運(yùn)金牌大戰(zhàn)",
"博彩賠率挺中國奪回第二紐約時報:中國因?qū)κ址幎鴣G失的獎牌最多",
"最“出柜”奧運(yùn)?同性之愛閃耀里約",
"下跪拜謝與洪荒之力一樣 都是真情流露"
]
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; //查詢前端有沒有傳入回調(diào)函數(shù)
if (callback) {
res.send(callback + '(' + JSON.stringify(data) + ')'); //數(shù)據(jù)以函數(shù)參數(shù)的方式傳給前端
} else {
res.send(data);
}
這樣我們就從test.com訪問到了a.test.com下的資源。

二、cors
CORS 全稱是跨域資源共享(Cross-Origin Resource Sharing),是一種 ajax 跨域請求資源的方式,支持現(xiàn)代瀏覽器,IE支持10以上。 實現(xiàn)方式很簡單,當(dāng)你使用 XMLHttpRequest 發(fā)送請求時,瀏覽器發(fā)現(xiàn)該請求不符合同源策略,會給該請求加一個請求頭:Origin,后臺進(jìn)行一系列處理,如果確定接受請求則在返回結(jié)果中加入一個響應(yīng)頭:Access-Control-Allow-Origin。 瀏覽器判斷該響應(yīng)頭中是否包含 Origin 的值,如果有則瀏覽器會處理響應(yīng),我們就可以拿到響應(yīng)數(shù)據(jù),如果不包含瀏覽器直接駁回,這時我們無法拿到響應(yīng)數(shù)據(jù)。所以 CORS 的表象是讓你覺得它與同源的 ajax 請求沒啥區(qū)別,代碼完全一樣 。
同樣以上面的列子來演示。首先JS部分,發(fā)起AJAX請求(與同域相同):
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è)置請求頭 "Access-Control-Allow-Origin":
var news = [
"第11日前瞻:中國沖擊4金 博爾特再戰(zhàn)200米羽球",
"正直播柴飚/洪煒出戰(zhàn) 男雙力爭會師決賽",
"女排將死磕巴西!郎平安排男陪練模仿對方核心",
"沒有中國選手和巨星的110米欄 我們還看嗎?",
"中英上演奧運(yùn)金牌大戰(zhàn)",
"博彩賠率挺中國奪回第二紐約時報:中國因?qū)κ址幎鴣G失的獎牌最多",
"最“出柜”奧運(yùn)?同性之愛閃耀里約",
"下跪拜謝與洪荒之力一樣 都是真情流露"
]
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ā)起的請求才可以調(diào)用本域下的資源
//res.header("Access-Control-Allow-Origin", "*"); //"*"表示任何域下發(fā)起請求都可以調(diào)用本域下的資源
res.send(data);
三、降域
降域是相對于iframe元素而言的 。
比如,域名為http://b.baidu.com/b (A)的網(wǎng)頁以iframe的形式嵌在域名為http://a.baidu.com/a (B)的網(wǎng)頁中,正常情況下,該請求不符合瀏覽器的同源策略,不能進(jìn)行跨域訪問。但是當(dāng)我們在兩個頁面中分別設(shè)置documet.domain = baidu.com的時候(注意:這個方法有一個限制就是域名中必須有相同的部分),B頁面就可以訪問到A頁面中的資源了。比如下面的代碼:
B頁面:
<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頁面:
<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>
通過a.test.com/a.html訪問b.test.com/b.html,實現(xiàn)了跨域訪問,效果如下:

四、postMessage
window.postMessage()是HTML5的新方法,IE8+支持。可以使用它來向其它的window對象發(fā)送數(shù)據(jù),無論這個window對象是屬于同源或不同源。
postMessage(data, origin)方法接收兩個參數(shù):
- data:要傳遞的數(shù)據(jù)。html5規(guī)范中提到該參數(shù)可以是JavaScript的任意基本類型或可復(fù)制的對象,然而并不是所有瀏覽器都做到了這點(diǎn),部分瀏覽器只能處理字符串參數(shù),所以我們在傳遞參數(shù)的時候需要使用JSON.stringify()方法對對象參數(shù)序列化,在低版本IE中引用json2.js可以實現(xiàn)類似效果。
- origin: 字符串參數(shù)。用來限定接收消息的那個window對象所在的域,如果不想限定域,可以使用通配符
*,這樣可以傳遞給任意窗口,如果要指定和當(dāng)前窗口同源的話設(shè)置為"/"。
同樣以上面的例子來說明postMessage()的原理(A頁面中嵌套了一個B頁面)
那么我們可以在A頁面中通過postMessage()方法向跨域的B頁面?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>
那么,我們怎么在B頁面上接收A頁面?zhèn)鬟f過來的數(shù)據(jù)呢,我們只要在B頁面監(jiān)聽window的message事件就可以,消息內(nèi)容儲存在該事件對象的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頁面發(fā)送數(shù)據(jù),A頁面接受數(shù)據(jù),只要在B頁面使用postMessage()方法,然后在A頁面監(jiān)聽window的message事件即可。
最終頁面得到的效果如下:

參考