1、什么是同源策略
浏览器出于安全考虑,只能同本域进行接口交互。不同源的客户端脚本在未经许可的情况下,不允许读写对方的资源。本域指的是协议、域名、端口都要相同:
1.协议,比如http和https是不同协议
2.域名,比如https://jirengu.com/a 和 https://bbs.jirengu.com/b 是不同域名
3.端口,比如https://jirengu.com:80 和 https://jirengu.com:8080 是不同端口
所以只要协议、域名、端口有任何一个不同,都被当作是不同的域。
2、什么是跨域?跨域有几种实现形式
跨域:跨域就是实现不同域的接口可以进行数据交互
实现跨域的方法:
序号 | 方法 |
---|---|
1 | JSONP |
2 | CORS(用了ajax) |
3 | 降域 |
4 | postMessage |
3、JSONP 的原理是什么
jsonp是json with padding(填充式json或参数式json)的简写。html中script标签可以引入其他域下的js,比如引入线上的jquery库。利用这个特性,可实现跨域访问接口,需要后端支持。其中src的链接会被当成js执行。
步骤 | 操作 |
---|---|
1 | 在页面上定义数据处理函数show |
2 | 创建script标签,src的地址执行后端接口,最后加个参数callback=show |
3 | 服务端在收到请求后,解析参数,计算返回数据,输出show(data)字符串 |
4 | show(data)会放到script标签作为js执行。此时会调用show函数,将data作为参数 |
//页面代码
<!doctype html>
<html>
<head></head>
<body>
<div class="newsWrap">
<ul>
<li>第11日前瞻:中国冲击4金 博尔特再战</li>
<li>男双力争会师决赛</li>
<li>女排将死磕巴西!</li>
</ul>
<div class="btn">
<button>换一组</button>
</div>
</div>
<script>
function $$(str){
return document.querySelector(str);
}
var btn=$$(".newsWrap .btn button");
var ul=$$(".newsWrap ul");
btn.addEventListener("click",function(){ //1、点击页面换一组
var script=document.createElement("script");
var src="http://localhost:8080/getNews?callback=getnew";
script.src=src;
document.head.appendChild(script); //2、向head添加script标签,向传输的地址发送请求,并提供参数callback=getnew
document.head.removeChild(script); //4、请求完成后,删除script标签
},false);
function getnew(str){ //5、页面接受数据getnews("["","",""]")后执行函数,把数据添加到页面上
var html="";
for(var i=0;i<str.length;i++){
html+="<li>"+str[i]+"</li>";
}
ul.innerHTML=html;
}
</script>
</body>
</html>
//后台代码
router.get('/getNews', function(req, res) {
var getnews = req.query.callback; // 通过 req.query获取请求参数
var news = [
"第11日前瞻:中国冲击4金 博尔特再战200米羽球",
"正直播柴飚/洪炜出战 男双力争会师决赛",
"女排将死磕巴西!郎平安排男陪练模仿对方核心",
"没有中国选手和巨星的110米栏 我们还看吗?",
"中英上演奥运金牌大战",
"博彩赔率挺中国夺回第二纽约时报:中国因对手服禁药而丢失的奖牌最多",
"最“出柜”奥运?同性之爱闪耀里约",
"下跪拜谢与洪荒之力一样 都是真情流露"
];
var arr=[],num=[-1],b;
for(var i=0;i<3;i++){
b=Math.floor(Math.random()*(news.length));
for(var j=0;j<num.length;j++){
if(b===num[j]) {i--;}
else {
arr.push(news[b]);
num.push(b); break;
}
};
};
res.send(getnews+"("+JSON.stringify(arr)+")"); //3、发送的数据为getnews("["","",""]");
});
4、CORS是什么
CORS 全称是跨域资源共享(Cross-Origin Resource Sharing),是一种 ajax 跨域请求资源的方式,支持现代浏览器,IE支持10以上。
实现方式很简单,当你使用 XMLHttpRequest 发送请求时,浏览器发现该请求不符合同源策略,会给该请求加一个请求头:Origin,后台进行一系列处理,如果确定接受请求则在返回结果中加入一个响应头:Access-Control-Allow-Origin;
浏览器判断该相应头中是否包含 Origin 的值,如果有则浏览器会处理响应,我们就可以拿到响应数据,如果不包含浏览器直接驳回,这时我们无法拿到响应数据。所以 CORS 的表象是让你觉得它与同源的 ajax 请求没啥区别,代码完全一样。
//假设这个页面的域名为http://a.jrg.com
<!doctype html>
<html>
<head></head>
<body>
<div class="newsWrap">
<ul>
<li>第11日前瞻:中国冲击4金 博尔特再战</li>
<li>男双力争会师决赛</li>
<li>女排将死磕巴西!</li>
</ul>
<div class="btn">
<button>换一组</button>
</div>
</div>
<script>
//CORS跨域获取数据
function $$(str){
return document.querySelector(str);
}
var btn=$$(".newsWrap .btn button");
var ul=$$(".newsWrap ul");
btn.addEventListener("click",function(){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200|| xhr.status===304){
getnew(JSON.parse(xhr.responseText));
}
else console.log("出错了");
}
}
xhr.open("get","http://b.jrg.com:8080/getNews",true); //向域名为http://b.jrg.com:8080请求数据
xhr.send();
},false);
</script>
</body>
</html>
router.get("/getNews",function(reg,res){
var getnews=reg.query.callback;
var news = [
"第11日前瞻:中国冲击4金 博尔特再战200米羽球",
"正直播柴飚/洪炜出战 男双力争会师决赛",
"女排将死磕巴西!郎平安排男陪练模仿对方核心",
"没有中国选手和巨星的110米栏 我们还看吗?",
"中英上演奥运金牌大战",
"博彩赔率挺中国夺回第二纽约时报:中国因对手服禁药而丢失的奖牌最多",
"最“出柜”奥运?同性之爱闪耀里约",
"下跪拜谢与洪荒之力一样 都是真情流露"
];
var arr=[],num=[-1],b;
for(var i=0;i<3;i++){
b=Math.floor(Math.random()*(news.length));
for(var j=0;j<num.length;j++){
if(b===num[j]) {i--;}
else {
arr.push(news[b]);
num.push(b); break;
}
};
};
res.header("Access-Control-Allow-Origin","http://a.jrg.com:8080"); //表示接受http://a.jrg.com:8080的请求
res.send(arr);
});
5、降域
如果两个窗口一级域名相同,只是二级域名不同,那么使用document.domain 属性,就可以对页面进行降域处理,拿到相应数据。
<div class="ct">
<h1>使用降域实现跨域</h1>
<div class="main">
<input type="text" placeholder="http://a.jrg.com:8080/a.html">
</div>
<iframe src="http://b.jrg.com:8080/b.html" frameborder="0" ></iframe>
</div>
<script>
//URL: http://a.jrg.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 = "jrg.com"; //设置document.domain的相同域名进行降域
</script>
<input id="input" type="text" placeholder="http://b.jrg.com:8080/b.html">
<script>
// URL: http://b.jrg.com:8080/b.html
document.querySelector('input').addEventListener('input',function(){
console.log(this.value);
window.parent.document.querySelector('.main input').value = this.value
})
document.domain = "jrg.com"; //设置document.domain的相同域名进行降域
</script>
6、PostMessage
window.postMessage()是HTML5的新方法,可以使用它来向其它的window对象发送数据,无论这个window对象是属于同源或不同源,IE8+支持。
otherWindow.postMessage(message, targetOrigin);
- otherWindow
其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。 - message
要传递的数据。html5规范中提到该参数可以是JavaScript的任意基本类型或可复制的对象,然而并不是所有浏览器都做到了这点儿,部分浏览器只能处理字符串参数,所以我们在传递参数的时候需要使用JSON.stringify()方法对对象参数序列化.
通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串""(表示无限制)或者一个URI。在发送消息的时候,如果目标窗口的协议、主机地址或端口这三者的任意一项不匹配targetOrigin提供的值,那么消息就不会被发送;只有三者完全匹配,消息才会被发送。这个机制用来控制消息可以发送到哪些窗口;例如,当用postMessage传送密码时,这个参数就显得尤为重要,必须保证它的值与这条包含密码的信息的预期接受者的orign属性完全一致,来防止密码被恶意的第三方截获。如果你明确的知道消息应该发送到哪个窗口,那么请始终提供一个有确切值的targetOrigin,而不是。不提供确切的目标将导致数据泄露到任何对数据感兴趣的恶意站点。
<script>
//URL: http://a.jrg.com:8080/a.html
$('.main input').addEventListener('input',function(){
console.log(this.value);
window.frames[0].postmessage(this.value,"http://b.jrg.com:8080/b.html"); //向b.jrg.com:8080/b.html发送数据
});
window.addEventListener('message',function(e){ //监听事件,当事件发生时接收数据
$('.main input') = e.data;
console.log(e.data);
});
function $(id){
return document.querySelector(id);
}
</script>
<script>
// URL: http://b.jrg.com:8080/b.html
$('input').addEventListener('input',function(){
console.log(this.value);
window.parent.postmessage(this.value,"http://a.jrg.com:8080/a.html"); //向a.jrg.com:8080/b.html发送数据
});
window.addEventListener('message',function(e){ ////监听事件,当事件发生时接收数据
$('input') = e.data;
console.log(e.data);
});
function $(id){
return document.querySelector(id);
}
</script>
(mission 13)