題目1: 什么是同源策略
題目2: 什么是跨域雏赦?跨域有幾種實(shí)現(xiàn)形式
- 跨域就是在不同本域下的接口進(jìn)行交互。
- 跨域的實(shí)現(xiàn)形式有:
1.JSONP芙扎。
2.CORS星岗。
3.降域。
4.postMessage戒洼。
題目3: JSONP 的原理是什么
- JSONP的原理是利用例如<script>中的"src"這個(gè)屬性俏橘,這個(gè)屬性可以不受瀏覽器的同源策略限制進(jìn)行跨域,不過(guò)需要后端支持圈浇。
- 具體步驟:
1.定義數(shù)據(jù)處理函數(shù)_fun
2.創(chuàng)建script標(biāo)簽寥掐,src的地址執(zhí)行后端接口,最后加個(gè)參數(shù)callback=_fun
3.服務(wù)端在收到請(qǐng)求后磷蜀,解析參數(shù)召耘,計(jì)算返還數(shù)據(jù),輸出 fun(data) 字符串蠕搜。
4..fun(data)會(huì)放到script標(biāo)簽做為js執(zhí)行怎茫。此時(shí)會(huì)調(diào)用fun函數(shù)收壕,將data做為參數(shù)妓灌。
題目4: CORS是什么
- CORS 全稱(chēng)是跨域資源共享(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ū)別箍镜,代碼完全一樣源祈。
題目5: 根據(jù)視頻里的講解演示三種以上跨域的解決方式 ,寫(xiě)成博客
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>news</title>
<style>
.container{
width: 900px;
margin: 0 auto;
}
</style>
</head>
<body>
<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>
<script>
$('.change').addEventListener('click', function(){
var script = document.createElement('script');
script.src = 'http://127.0.0.1/getNews?callback=appendHtml';//創(chuàng)建一個(gè)<script>標(biāo)簽香缺,并且設(shè)置它的src屬性為需要請(qǐng)求的地址,設(shè)置返回的包裹函數(shù)名字為appendHtml.
document.head.appendChild(script);
document.head.removeChild(script);//在head中添加這個(gè)標(biāo)簽歇僧,運(yùn)行之后再刪除图张,以免重復(fù)點(diǎn)擊增加代碼行數(shù)
})
function appendHtml(news){
var html = '';
for( var i=0; i<news.length; i++){
html += '<li>' + news[i] + '</li>';
}//在數(shù)據(jù)到來(lái)之前先設(shè)置好函數(shù)的內(nèi)容,讓數(shù)據(jù)到來(lái)之后便直接運(yùn)行诈悍。
console.log(html);
$('.news').innerHTML = html;
}
function $(id){
return document.querySelector(id);
}
</script>
</html>
app.get('/getNews', function(req, res){
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 = parseInt(Math.random()*news.length);
data.push(news[index]);
news.splice(index, 1);
}
var cb = req.query.callback;//在請(qǐng)求到來(lái)的時(shí)候確認(rèn)是否需要包裹函數(shù)倔撞,也就是后端需要配合的地方。
if(cb){
res.send(cb + '('+ JSON.stringify(data) + ')');
}else{
res.send(data);
}
})
- JSONP主要思路就是利用<script>標(biāo)簽的src屬性不受同源策略的限制來(lái)進(jìn)行跨域慕趴』居可以理解為大路走不通,另外走一條小路來(lái)到達(dá)目的地冕房□飭可以直接將JSONP封裝成一個(gè)函數(shù),以便反復(fù)調(diào)用耙册,與AJAX使用方法類(lèi)似给僵,但是原理完全不同。
function jsonp(url,data,callback){
var script = document.createElement('script');//創(chuàng)建一個(gè)script標(biāo)簽
url = url + "?callback=" + callback;//拼接回調(diào)函數(shù)名字
if(data){
for(key in data){
url = url + "&" + key + "=" + data[key];//如果有需要的參數(shù)輸入,將參數(shù)也拼接進(jìn)url
}
}
script.src = url帝际;
document.head.appendChild(script);//創(chuàng)建script標(biāo)簽發(fā)送請(qǐng)求蔓同。
document.head.removeChild(script);//完成之后刪除窗前的script標(biāo)簽。
}
function callback(){
data[1] = ...........
}
- CORS前端寫(xiě)法蹲诀,與ajax沒(méi)有區(qū)別斑粱,區(qū)別主要在于后端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>news</title>
<style>
.container{
width: 900px;
margin: 0 auto;
}
</style>
</head>
<body>
<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>
<script>
$('.change').addEventListener('click', function(){
var xhr = new XMLHttpRequest();
xhr.open('get', 'http://b.jrg.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>';
}
console.log(html);
$('.news').innerHTML = html;
}
function $(id){
return document.querySelector(id);
}
</script>
</html>
- CORS后端寫(xiě)法脯爪,需要在返回?cái)?shù)據(jù)的響應(yīng)頭前加上"Access-Control-Allow-Origin"则北,并且寫(xiě)上允許的地址,如果寫(xiě)"*",則表示允許所有地址從這里獲得數(shù)據(jù)痕慢∩写В可以理解為大路被障礙封鎖,疏通障礙之后再走掖举。缺點(diǎn)是只有ie10以上的瀏覽器才會(huì)兼容惑艇。
app.get('/getNews', function(req, res){
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 = parseInt(Math.random()*news.length);
data.push(news[index]);
news.splice(index, 1);
}
res.header("Access-Control-Allow-Origin", "http://a.jrg.com:8080");
//res.header("Access-Control-Allow-Origin", "*");
res.send(data);
})
- window.postMessage() 方法提供了一種受控機(jī)制來(lái)規(guī)避同源策略限制,只要正確的使用俺叭,這種方法就很安全恭取。它可以讓一個(gè)特定的地址(第二個(gè)參數(shù),如果寫(xiě)"*"則表示所有地址都允許)來(lái)獲取某個(gè)參數(shù)(第一個(gè)參數(shù))熄守。
- postMessage——a.html
<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>使用postMessage實(shí)現(xiàn)跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.jrg.com:8080/a.html">
</div>
<iframe src="http://localhost:8080/b.html" frameborder="0" ></iframe>
</div>
<script>
//URL: http://a.jrg.com:8080/a.html
$('.main input').addEventListener('input', function(){
console.log(this.value);
window.frames[0].postMessage(this.value,'*');
})
window.addEventListener('message',function(e) {
$('.main input').value = e.data
console.log(e.data);
});
function $(id){
return document.querySelector(id);
}
</script>
</html>
<html>
<style>
html,body{
margin: 0;
}
input{
margin: 20px;
width: 200px;
}
</style>
<input id="input" type="text" placeholder="http://b.jrg.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
$('#input').addEventListener('input', function(){
window.parent.postMessage(this.value, '*');
})
window.addEventListener('message',function(e) {
$('#input').value = e.data
console.log(e.data);
});
function $(id){
return document.querySelector(id);
}
</script>
</html>