一、 跨域请求的含义
浏览器的同源策略,出于防范跨站脚本的攻击,禁止客户端脚本(如 JavaScript)对不同域的服务进行跨站调用。
一般的,只要网站的 协议名protocol
、 主机host
、 端口号port
这三个中的任意一个不同,网站间的数据请求与传输便构成了跨域调用。这也是我们下面实践的理论基础。我们利用 NodeJs 创建了两个服务器,分别监听 3000
、 3001
端口(下面简称 服务器3000 与 服务器3001 ),由于端口号不一样,这两个服务器以及服务器上页面通信构成了跨域请求。
1.什么是跨域
跨域是指一个域下的文档或者脚本试图去请求另一个域下的资源.
广义的跨域: ① 资源的跳转 链接 网页重定向 表单提交
② 资源嵌入: <link>、<script>、<img>、<frame>等dom标签,还有样式中background:url()、@font-face()等文件外链
③ 脚本请求 : js发起的ajax请求 dom和js对象的跨域操作
2.什么是同源策略
同源策略是浏览器最核心也最按基本的安全功能,缺少了同源策略,浏览器很容易受到xss、csfr等攻击.
同源: 网络协议 域名 端口 三者相同 .
同源策略限制一下几种行为:
1. cookie localstorage 和 indexdb 无法读取
2. dom 和 js对象无法获得
3. ajax 请求不能发送
3.常见跨域场景
URL 说明 是否允许通信
http://www.domain.com/a.js
http://www.main.com/b.js 同一域名,不同文件或路径 允许
http://www.main.com/lab/c.js
http://www.main.com:8000/a.js
http://www.main.com/b.js 同一域名,不同端口 不允许
http://www.main.com/a.js
https://www.main.com/b.js 同一域名,不同协议 不允许
http://www.main.com/a.js
http://192.168.1.9/b.js 域名和域名对应相同ip 不允许
http://www.main.com/a.js
http://x.main.com/b.js 主域相同,子域不同 不允许
http://main.com/c.js
http://www.main1.com/a.js
http://www.main2.com/b.js 不同域名 不允许
4.跨域解决方案
1、 通过jsonp跨域
2、 document.domain + iframe跨域
3、 location.hash + iframe
4、 window.name + iframe跨域
5、 postMessage跨域
6、 跨域资源共享(CORS)
7、 nginx代理跨域
8、 nodejs中间件代理跨域
9、 WebSocket协议跨域
1.通过jsonp跨域
为了减轻web服务器的负载,通常把js css img等静态资源分离到另外一台独立域名的服务器上,在html页面中通过 相应的标签从不同域名下加载静态资源,而被浏览器允许,基于此原理,我们可以通过动态创建script标签,再请求一个 带参网址实现跨域通信.
① 原生实现:
<script>
var script = document.createElement('script');
script.type = 'text/javascript';
// 传参并指定回调执行函数为onBack
script.src = 'http://www.main2.com:8080/login?user=admin&callback=onBack';
document.head.appendChild(script);
// 回调执行函数
function onBack(res) {
alert(JSON.stringify(res));
}
</script>
服务端返回如下(返回时即执行全局函数):
onBack({"status": true, "user": "admin"})
②.jquery ajax:
$.ajax({
url: 'http://www.main2.com:8080/login',
type: 'get',
dataType: 'jsonp', // 请求方式为jsonp
jsonpCallback: "onBack", // 自定义回调函数名
data: {}
});
③. vue.js
this.$http.jsonp('http://www.main2.com:8080/login', {
params: {},
jsonp: 'onBack'
}).then((res) => {
console.log(res);
})
后端node.js代码示例:
var querystring = require('querystring');
var http = require('http');
var server = http.createServer();
server.on('request', function (req, res) {
var params = qs.parse(req.url.split('?')[1]);
var fn = params.callback;
// jsonp返回设置
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.write(fn + '(' + JSON.stringify(params) + ')');
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
jsonp缺点: 只能实现get一种请求
2. document.domain + iframe 跨域 (主域相同 子域不同)
实现原理: 两个页面都通过js强制设置document.domainwei基础主域 就实现了同域
// 父窗口:(http://www.main.com/a.html)
<iframe id="iframe" src="http://child.main.com/b.html"></iframe>
document.domain = 'domain.com';
var user = 'admin';
// 子窗口:(http://child.main.com/b.html)
document.domain = 'main.com';
// 获取父窗口中变量
alert('get js data from parent ---> ' + window.parent.user);
3. location.hash + iframe 跨域
实现原理: a 要与b跨域互相通信 通过中间页c来实现 不同域之间利用iframe的 location.hash传值,相同域名之间直接js访问来通信
具体实现: A域:a.html -> B域:b.html -> A域:c.html,a与b不同域只能通过hash值单向通信,b与c也不同域也只能单向通信,但c与a同域,所以c可通过parent.parent访问a页面所有对象。
1.)a.html:(http://www.domain1.com/a.html)
<iframe id="iframe" src="http://www.domain2.com/b.html"
style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
// 向b.html传hash值
setTimeout(function() {
iframe.src = iframe.src + '#user=admin';
}, 1000);
// 开放给同域c.html的回调方法
function onCallback(res) {
alert('data from c.html ---> ' + res);
}
</script>
2.)b.html:(http://www.domain2.com/b.html)
<iframe id="iframe" src="http://www.domain1.com/c.html"
style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
// 监听a.html传来的hash值,再传给c.html
window.onhashchange = function () {
iframe.src = iframe.src + location.hash;
};
</script>
3.)c.html:(http://www.domain1.com/c.html)
<script>
// 监听b.html传来的hash值
window.onhashchange = function () {
// 再通过操作同域a.html的js回调,将结果传回
window.parent.parent.onCallback('hello: '
+ location.hash.replace('#user=', ''));
};
</script>
4. window.name + iframe 跨域
window.name属性的独特之处:name值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。
1.)a.html:(http://www.domain1.com/a.html)
<script>
var proxy = function (url, callback) {
var state = 0;
var iframe = document.createElement('iframe');
// 加载跨域页面
iframe.src = url;
// onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
iframe.onload = function () {
if (state === 1) {
// 第2次onload(同域proxy页)成功后,读取同域window.name中数据
callback(iframe.contentWindow.name);
destoryFrame();
} else if (state === 0) {
// 第1次onload(跨域页)成功后,切换到同域代理页面
iframe.contentWindow.location =
'http://www.domain1.com/proxy.html';
state = 1;
}
};
document.body.appendChild(iframe);
// 获取数据以后销毁这个iframe,释放内存;这也保证了安全(
不被其他域frame js访问)
function destoryFrame() {
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
}
};
// 请求跨域b页面数据
proxy('http://www.domain2.com/b.html', function (data) {
alert(data);
});
</script>
2.)proxy.html:(http://www.domain1.com/proxy.... 中间代理页,与a.html同域,
内容为空即可。
3.)b.html:(http://www.domain2.com/b.html)
<script>
window.name = 'This is domain2 data!';
</script>
总结:通过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name
从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。
5. postMessage 跨域
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是为数不多可以跨域操作的window属性之一,它可用于解决以下方面的问题:
a.) 页面和其打开的新窗口的数据传递
b.) 多窗口之间消息传递
c.) 页面与嵌套的iframe消息传递
d.) 上面三个场景的跨域数据传递
用法:postMessage(data,origin)方法接受两个参数
data: html5规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用JSON.stringify()序列化。
origin: 协议+主机+端口号,也可以设置为"*",表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。
1.)a.html:(http://www.domain1.com/a.html)
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
iframe.onload = function() {
var data = {
name: 'aym'
};
// 向domain2传送跨域数据
iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
};
// 接受domain2返回数据
window.addEventListener('message', function(e) {
alert('data from domain2 ---> ' + e.data);
}, false);
</script>
2.)b.html:(http://www.domain2.com/b.html)
<script>
// 接收domain1的数据
window.addEventListener('message', function(e) {
alert('data from domain1 ---> ' + e.data);
var data = JSON.parse(e.data);
if (data) {
data.number = 16;
// 处理后再发回domain1
window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');
}
}, false);
</script>