聲明
本人也在不斷的學(xué)習(xí)和積累中,文章中有不足和誤導(dǎo)的地方還請(qǐng)見(jiàn)諒,可以給我留言指正。希望和大家共同進(jìn)步,共建和諧學(xué)習(xí)環(huán)境。
跨域
?1、什么是跨域
指的是瀏覽器不能執(zhí)行其他網(wǎng)站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對(duì)javascript施加的安全限制。
?2、同源策略
是指協(xié)議,域名,端口都要相同,其中有一個(gè)不同都會(huì)產(chǎn)生跨域;
跨域示例
?3、同源策略限制以下行為:
- Cookie、LocalStorage 和 IndexDB 無(wú)法讀取
- DOM 和 JS 對(duì)象無(wú)法獲取
- Ajax請(qǐng)求發(fā)送不出去
解決方案
?據(jù)我了解的,總結(jié)了以下幾種方式,有其他方式的可以給我留言:
- domain設(shè)置,只適用于子域
- jsonp方法,只適用于get請(qǐng)求
- CROS,(跨域資源共享協(xié)議),適用于各種請(qǐng)求
- post Message,適用于父子網(wǎng)頁(yè)iframe通信
- location.hash, 數(shù)據(jù)直接暴露在了url中,數(shù)據(jù)容量和類(lèi)型都有限
- Nginx 代理
?1、domain
??假設(shè)我們現(xiàn)在有一個(gè)頁(yè)面 a.html 它的地址為http://www.a.com/a.html , 在a.html 在中有一個(gè)iframe,iframe的src為http://a.com/b.html,這個(gè)頁(yè)面與它里面的iframe框架是不同域的,所以我們是無(wú)法通過(guò)在頁(yè)面中書(shū)寫(xiě)js代碼來(lái)獲取iframe中的東西的;
??a.html內(nèi)容:
<script type="text/javascript">
function test(){
var iframe = document.getElementById('ifame');
var win = document.contentWindow;
var doc = win.document;//這里獲取不到iframe里的document對(duì)象
var name = win.name;//這里同樣獲取不到window對(duì)象的name屬性
}
</script>
<iframe id = "iframe" src="http://a.com/b.html" onload = "test()"></iframe>
??使用domain設(shè)置,a.html中的內(nèi)容修改為:
<iframe id = "iframe" src="http://a.com/b.html" onload = "test()"></iframe>
<script type="text/javascript">
document.domain = 'a.com'; //設(shè)置成主域
function test(){
alert(document.getElementById('iframe').contentWindow); //contentWindow 可取得子窗口的 window 對(duì)象
}
</script>
??在b.html 中也設(shè)置
<script type="text/javascript">
document.domain = 'a.com';//在iframe載入這個(gè)頁(yè)面也設(shè)置document.domain,使之與主頁(yè)面的document.domain相同
</script>
?2、jsonp
??采用這種方法,是由于html標(biāo)簽src屬性不受同源限制。
??優(yōu)點(diǎn):它不像XMLHttpRequest對(duì)象實(shí)現(xiàn)的Ajax請(qǐng)求那樣受到同源策略的限制;它的兼容性更好,在更加古老的瀏覽器中都可以運(yùn)行,不需要XMLHttpRequest或ActiveX的支持;并且在請(qǐng)求完畢后可以通過(guò)調(diào)用callback的方式回傳結(jié)果。
??缺點(diǎn):它只支持GET請(qǐng)求而不支持POST等其它類(lèi)型的HTTP請(qǐng)求;它只支持跨域HTTP請(qǐng)求這種情況,不能解決不同域的兩個(gè)頁(yè)面之間如何進(jìn)行JavaScript調(diào)用的問(wèn)題。
??原生方法:
function jsonp({url,callback}) {
let script = document.createElement('script');
script.src = `${url}&callback=${callback}`;
document.head.appendChild(script);
}
??node服務(wù):
const http = require('http');
const url = require('url');
const queryString = require('querystring');
const data = JSON.stringify({
title: 'hello,jsonp!'
})
const server = http.createServer((request, response) => {
let addr = url.parse(request.url);
if (addr.pathname == '/jsonp') {
let cb = queryString.parse(addr.query).callback;
response.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' })
response.write(cb + '('+ data +')'); // 回調(diào)
} else {
response.writeHead(403, { 'Content-Type': 'text/plain;charset=utf-8' })
response.write('403');
}
response.end();
})
server.listen(3000, () => {
console.log('Server is running on port 3000!');
})
??頁(yè)面調(diào)用:
jsonp({
url: 'http://localhost:3000/jsonp?from=1',
callback: 'getData',
})
function getData(res) {
console.log(res); // {title: "hello,jsonp!"}
}
??jQuery方法:
$(function () {
$.ajax({
url: 'http://localhost:3000/jsonp?from=1',
type: 'get',
dataType: 'jsonp',
success: function(res) {
console.log(res); // {title: "hello,jsonp!"}
}
})
})
?3、CROS
??CORS(Cross -Origin Resource Sharing),跨域資源共享,是一個(gè)W3C標(biāo)準(zhǔn),在http的基礎(chǔ)上發(fā)布的標(biāo)準(zhǔn)協(xié)議。
??CORS需要游覽器和服務(wù)器同時(shí)支持,解決了游覽器的同源限制,使得跨域資源請(qǐng)求得以實(shí)現(xiàn)。它有兩種請(qǐng)求,一種是簡(jiǎn)單請(qǐng)求,另外一種是非簡(jiǎn)單請(qǐng)求。
簡(jiǎn)單請(qǐng)求
滿(mǎn)足以下兩個(gè)條件就屬于簡(jiǎn)單請(qǐng)求,反之非簡(jiǎn)單。
- 請(qǐng)求方式是 GET、POST、HEAD;
- 響應(yīng)頭信息是 Accept、Accept-Language、Content-Language、Last-Event-ID、Content-Type(只限于application/x-www-form-urlencoded、multipart/form-data、text/plain);
- 簡(jiǎn)單請(qǐng)求
有三個(gè)CORS字段需要加在響應(yīng)頭中,前面部分都是以Access-Control開(kāi)頭:
? 1、Access-Control-Allow-Origin,這個(gè)表示接受哪些域名的請(qǐng)求,如果是*號(hào),那就是任何域名都可以請(qǐng)求;
? 2、Access-Control-Allow-Credentials,這個(gè)表示是否允許攜帶cookie,默認(rèn)是false,不允許攜帶;
? ? 如果設(shè)置為true, 要發(fā)送cookie,允許域就必須指定域名方法;客戶(hù)端http請(qǐng)求必須設(shè)置:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
? 3、Access-Control-Expose-Headers,這個(gè)表示服務(wù)器可接受的響應(yīng)頭字段,如果客戶(hù)端發(fā)送過(guò)來(lái)請(qǐng)求攜帶的Cache-Control、Content-Language、Content-Type、Expires、Last-Modified,還有自定義請(qǐng)求頭字段。
- 非簡(jiǎn)單請(qǐng)求
? 就是除了簡(jiǎn)單請(qǐng)求的幾種方法外,比如說(shuō)PUT請(qǐng)求、DELETE請(qǐng)求,這種都是要發(fā)一個(gè)預(yù)檢請(qǐng)求的,然后服務(wù)器允許,才會(huì)發(fā)送真正的請(qǐng)求。
? 非簡(jiǎn)單請(qǐng)求有以下幾個(gè)字段需要傳遞:
? 1、Access-Control-Allow-Methods,值是以逗號(hào)分隔,比如:GET,POST,DELETE;
? 2、Access-Control-Allow-Headers,值是默認(rèn)字段或者自定義字段,例如:X-Auth-Info;
? 3、Access-Control-Allow-Credentials,是否攜帶cookie信息;
? 4、Access-Control-Max-Age,代表預(yù)檢請(qǐng)求的有效期限,單位是秒。
?4、post Message
- otherWindow.postMessage(message, targetOrigin);
otherWindow:指目標(biāo)窗口,也就是給哪個(gè)window發(fā)消息,是 window.frames 屬性的成員或者由 window.open 方法創(chuàng)建的窗口
message: 是要發(fā)送的消息,類(lèi)型為 String、Object (IE8、9 不支持)
targetOrigin: 是限定消息接收范圍,不限制請(qǐng)使用 ‘*
??父頁(yè)面通過(guò)postMessage('<msg>','<url>'),子頁(yè)面接收消息,并且返回消息到父頁(yè)面,父頁(yè)面監(jiān)聽(tīng)message事件接收消息。
??例如:http://map.domaintest.org:8089/parent.html發(fā)送消息給子頁(yè)面http://map.domaintest.org:8089/son.html,子頁(yè)面返回消息。
- 父頁(yè)面的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>父級(jí)頁(yè)面</title>
</head>
<body>
<button id="btn">發(fā)送消息</button>
<iframe id="child" src="http://map.domaintest.org:8089/son.html" width="100%" height="300"></iframe>
<script>
let sendBtn = document.querySelector('#btn');
sendBtn.addEventListener('click', sendMsg, false);
function sendMsg () {
window.frames[0].postMessage('getMsg', 'http://map.domaintest.org:8089/son.html');
}
window.addEventListener('message', function (e) {
let data = e.data;
console.log('接收到的消息是:'+ data);
})
</script>
</body>
</html>
- 子頁(yè)面的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>子頁(yè)面</title>
</head>
<body>
<h2>窗口</h2>
<p>我是另外一個(gè)窗口!</p>
<script>
window.addEventListener('message', function (e) {
if (e.source != window.parent) return;
window.parent.postMessage('我是來(lái)自子頁(yè)面的消息!', '*');
}, false)
</script>
</body>
</html>
?5、location.hash
?原理:父窗口可以對(duì)iframe進(jìn)行URL讀寫(xiě),iframe也可以讀寫(xiě)父窗口的URL,動(dòng)態(tài)插入一個(gè)iframe然后設(shè)置其src為服務(wù)端地址,而服務(wù)端同樣輸出一端js代碼,也同時(shí)通過(guò)與子窗口之間的通信來(lái)完成數(shù)據(jù)的傳輸。
?假如父頁(yè)面是baidu.com/a.html,iframe嵌入的頁(yè)面為google.com/b.html(此處省略了域名等url屬性),要實(shí)現(xiàn)此兩個(gè)頁(yè)面間的通信可以通過(guò)以下方法。
- a.html傳送數(shù)據(jù)到b.html
- a.html下修改iframe的src為
google.com/b.html#paco - b.html監(jiān)聽(tīng)到url發(fā)生變化,觸發(fā)相應(yīng)操作
- b.html傳送數(shù)據(jù)到a.html,由于兩個(gè)頁(yè)面不在同一個(gè)域下IE、Chrome不允許修改parent.location.hash的值,所以要借助于父窗口域名下的一個(gè)代理iframe
- b.html下創(chuàng)建一個(gè)隱藏的iframe,此iframe的src是baidu.com域下的,并掛上要傳送的hash數(shù)據(jù),如src=”
http://www.baidu.com/proxy.html#data” - proxy.html監(jiān)聽(tīng)到url發(fā)生變化,修改a.html的url(因?yàn)閍.html和proxy.html同域,所以proxy.html可修改a.html的url hash)
- a.html監(jiān)聽(tīng)到url發(fā)生變化,觸發(fā)相應(yīng)操作
?b.html內(nèi)容:
try {
parent.location.hash = 'data';
} catch (e) {
// ie、chrome的安全機(jī)制無(wú)法修改parent.location.hash,
var ifrproxy = document.createElement('iframe');
ifrproxy.style.display = 'none';
ifrproxy.src = "http://www.baidu.com/proxy.html#data";
document.body.appendChild(ifrproxy);
}
?proxy.html內(nèi)容:
//因?yàn)閜arent.parent(即baidu.com/a.html)和baidu.com/proxy.html屬于同一個(gè)域,所以可以改變其location.hash的值
parent.parent.location.hash = self.location.hash.substring(1);
?6、Nginx配置
??利用nginx作為反向代理
server {
listen 80; #監(jiān)聽(tīng)80端口,可以改成其他端口
server_name localhost; # 當(dāng)前服務(wù)的域名
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://localhost:81;
proxy_redirect default;
}
location /apis { #添加訪問(wèn)目錄為/apis的代理配置
rewrite ^/apis/(.*)$ /$1 break;
proxy_pass http://localhost:82;
}
#....省略下面的配置
}
