A
连接、重定向、表单提交<link>
、<script>
、<img>
、<frame>
等dom
标签,还有样式中background:url()
、@font-face()
等文件外链js
发起的ajax
请求、dom
和js
对象的跨域操做等其实咱们一般所说的跨域是狭义的,是由浏览器同源策略限制的一类请求场景。javascript
同源策略,SOP(Same origin policy)
是一种约定,由Netscape
公司1995年引入浏览器,它是浏览器最核心也最基本的安全功能,若是缺乏了同源策略,浏览器很容易受到XSS
、CSFR
等攻击。所谓同源是指"协议+域名+端口"
三者相同,即使两个不一样的域名指向同一个ip地址,也非同源。 同源策略限制如下几种行为:css
Cookie
、LocalStorage
和 IndexDB
没法读取DOM
和 Js
对象没法得到AJAX
请求不能发送http://www.domain.com/a.js
、http://www.domain.com/b.js
同一域名,不一样文件或路径http://www.domain.com/a.js
、https://www.domain.com/b.js
同一域名,不一样协议 不容许http://www.domain.com/a.js
、http://192.168.4.12/b.js
域名和域名对应相同ip 不容许http://www.domain.com/a.js
、http://x.domain.com/b.js
主域相同,子域不一样 不容许http://domain.com/c.js
http://www.domain1.com/a.js
、http://www.domain2.com/b.js
不一样域名 不容许http://www.domain.com/lab/c.js
、http://www.domain.com:8000/a.js
、http://www.domain.com/b.js
同一域名,不一样端口 不容许jsonp
跨域 +document.domain + iframe
跨域location.hash + iframe
window.name + iframe
跨域postMessage
跨域(CORS)
nginx
代理跨域nodejs
中间件代理跨域WebSocket
协议跨域一般为了减轻web
服务器的负载,咱们把js
、css
,img
等静态资源分离到另外一台独立域名的服务器上,在html
页面中再经过相应的标签从不一样域名下加载静态资源,而被浏览器容许,基于此原理,咱们能够经过动态建立script
,再请求一个带参网址实现跨域通讯。html
<script>
var script = document.createElement('script');
script.type = 'text/javascript';
// 传参并指定回调执行函数为onBack
script.src = 'http://www.domain2.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.domain2.com:8080/login',
type: 'get',
dataType: 'jsonp', // 请求方式为jsonp
jsonpCallback: "onBack", // 自定义回调函数名
data: {}
});
复制代码
vue.js
:this.$http.jsonp('http://www.domain2.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一种请求vue
此方案仅限主域相同,子域不一样的跨域应用场景。 实现原理:两个页面都经过js强制设置document.domain为基础主域,就实现了同域。html5
(www.domain.com/a.html)
<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script> document.domain = 'domain.com'; var user = 'admin'; </script>
复制代码
(child.domain.com/b.html)
<script>
document.domain = 'domain.com';
// 获取父窗口中变量
alert('get js data from parent ---> ' + window.parent.user);
</script>
复制代码
实现原理: a
欲与b
跨域相互通讯,经过中间页c
来实现。 三个页面,不一样域之间利用iframe
的location.hash
传值,相同域之间直接js
访问来通讯。java
具体实现:A域:a.html -> B域:b.html -> A域:c.html
,a
与b
不一样域只能经过hash
值单向通讯,b
与c
也不一样域也只能单向通讯,但c
与a
同域,因此c
可经过parent.parent
访问a
页面全部对象。node
a.html:(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:(www.domain2.com/b.html)
jquery
<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>
复制代码
c.html:(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>
复制代码
window.name
属性的独特之处:name
值在不一样的页面(甚至不一样域名)加载后依旧存在,而且能够支持很是长的 name
值(2MB)。webpack
a.html:(www.domain1.com/a.html)
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);
});
复制代码
2.proxy.html:(www.domain1.com/proxy....
中间代理页,与··a.htm··l同域,内容为空便可。
b.html:(www.domain2.com/b.html)
<script>
window.name = 'This is domain2 data!';
</script>
复制代码
总结:经过 iframe
的 src
属性由外域转向本地域,跨域数据即由iframe
的window.name
从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操做。
postMessage
是HTML5 XMLHttpRequest Level 2
中的API
,且是为数很少能够跨域操做的 window
属性之一,它可用于解决如下方面的问题:
iframe
消息传递用法:postMessage(data,origin)
方法接受两个参数 data: html5
规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,因此传参时最好用JSON.stringify()
序列化。 origin: 协议+主机+端口号
,也能够设置为"*"
,表示能够传递给任意窗口,若是要指定和当前窗口同源的话设置为"/"
。
a.html:(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>
复制代码
b.html:(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>
复制代码
普通跨域请求:只服务端设置Access-Control-Allow-Origin
便可,前端无须设置。 带cookie请求:先后端都须要设置字段,所带cookie
为跨域请求接口所在域的cookie
,而非当前页。 目前,全部浏览器都支持该功能(IE8+
:IE8/9
须要使用XDomainRequest
对象来支持CORS
)),CORS
也已经成为主流的跨域解决方案。
ajax
// 前端设置是否带cookie
xhr.withCredentials = true;
示例代码:
var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
// 前端设置是否带cookie
xhr.withCredentials = true;
xhr.open('post', 'http://www.domain2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
复制代码
+jQuery ajax
$.ajax({
...
xhrFields: {
withCredentials: true // 前端设置是否带cookie
},
crossDomain: true, // 会让请求头中包含跨域的额外信息,但不会含cookie
...
});
复制代码
vue
框架在vue-resource
封装的ajax
组件中加入如下代码:Vue.http.options.credentials = true
复制代码
/* * 导入包:import javax.servlet.http.HttpServletResponse; * 接口参数中定义:HttpServletResponse response */
response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com"); // 如有端口需写全(协议+域名+端口)
response.setHeader("Access-Control-Allow-Credentials", "true");
复制代码
var http = require('http');
var server = http.createServer();
var qs = require('querystring');
server.on('request', function(req, res) {
var postData = '';
// 数据块接收中
req.addListener('data', function(chunk) {
postData += chunk;
});
// 数据接收完毕
req.addListener('end', function() {
postData = qs.parse(postData);
// 跨域后台设置
res.writeHead(200, {
'Access-Control-Allow-Credentials': 'true', // 后端容许发送Cookie
'Access-Control-Allow-Origin': 'http://www.domain1.com', // 容许访问的域(协议+域名+端口)
'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly:脚本没法读取cookie
});
res.write(JSON.stringify(postData));
res.end();
});
});
server.listen('8080');
console.log('Server is running at port 8080...');
复制代码
js、css、img
等常规静态资源被同源策略许可,但 iconfont
字体文件(eot|otf|ttf|woff|svg)
例外,此时可在nginx
的静态资源服务器中加入如下配置。location / {
add_header Access-Control-Allow-Origin *;
}
复制代码
HTTP
协议的一部分。服务器端调用HTTP
接口只是使用HTTP
协议,不会执行JS
脚本,不须要同源策略,也就不存在跨越问题。实现思路:经过nginx
配置一个代理服务器(域名与domain1
相同,端口不一样)作跳板机,反向代理访问domain2
接口,而且能够顺便修改cookie
中domain
信息,方便当前域cookie
写入,实现跨域登陆。
#proxy服务器server {
listen 81;
server_name www.domain1.com;
location / {
proxy_pass http://www.domain2.com:8080; #反向代理
proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名
index index.html index.htm;
# 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用
add_header Access-Control-Allow-Origin http://www.domain1.com; #当前端只跨域不带cookie时,可为*
add_header Access-Control-Allow-Credentials true;
}
}
复制代码
var xhr = new XMLHttpRequest();
// 前端开关:浏览器是否读写cookie
xhr.withCredentials = true;
// 访问nginx中的代理服务器
xhr.open('get', 'http://www.domain1.com:81/?user=admin', true);
xhr.send();
复制代码
var http = require('http');
var server = http.createServer();
var qs = require('querystring');
server.on('request', function(req, res) {
var params = qs.parse(req.url.substring(2));
// 向前台写cookie
res.writeHead(200, {
'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly:脚本没法读取
});
res.write(JSON.stringify(params));
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
复制代码
node
中间件实现跨域代理,原理大体与nginx
相同,都是经过启一个代理服务器,实现数据的转发。
vue
框架的跨域(2次跨域) 利用node + express + http-proxy-middleware
搭建一个proxy
服务器。var xhr = new XMLHttpRequest();
// 前端开关:浏览器是否读写cookie
xhr.withCredentials = true;
// 访问http-proxy-middleware代理服务器
xhr.open('get', 'http://www.domain1.com:3000/login?user=admin', true);
xhr.send();
复制代码
var express = require('express');
var proxy = require('http-proxy-middleware');
var app = express();
app.use('/', proxy({
// 代理跨域目标接口
target: 'http://www.domain2.com:8080',
changeOrigin: true,
// 修改响应头信息,实现跨域并容许带cookie
onProxyRes: function(proxyRes, req, res) {
res.header('Access-Control-Allow-Origin', 'http://www.domain1.com');
res.header('Access-Control-Allow-Credentials', 'true');
},
// 修改响应信息中的cookie域名
cookieDomainRewrite: 'www.domain1.com' // 能够为false,表示不修改
}));
app.listen(3000);
console.log('Proxy server is listen at port 3000...');
复制代码
Nodejs
后台同上面的nginx
vue
框架的跨域(1次跨域) 利用node + webpack + webpack-dev-server
代理接口跨域。在开发环境下,因为vue
渲染服务和接口代理服务都是webpack-dev-server
同一个,因此页面与代理接口之间再也不跨域,无须设置headers
跨域信息了。webpack.config.js
部分配置:module.exports = {
entry: {},
module: {},
...
devServer: {
historyApiFallback: true,
proxy: [{
context: '/login',
target: 'http://www.domain2.com:8080', // 代理跨域目标接口
changeOrigin: true,
cookieDomainRewrite: 'www.domain1.com' // 能够为false,表示不修改
}],
noInfo: true
}
}
复制代码
WebSocket protocol
是HTML5
一种新的协议。它实现了浏览器与服务器全双工通讯,同时容许跨域通信,是server push
技术的一种很好的实现。原生WebSocket API
使用起来不太方便,咱们使用Socket.io
,它很好地封装了webSocket
接口,提供了更简单、灵活的接口,也对不支持webSocket
的浏览器提供了向下兼容。
<div>user input:<input type="text"></div>
<script src="./socket.io.js"></script>
<script> var socket = io('http://www.domain2.com:8080'); // 链接成功处理 socket.on('connect', function() { // 监听服务端消息 socket.on('message', function(msg) { console.log('data from server: ---> ' + msg); }); // 监听服务端关闭 socket.on('disconnect', function() { console.log('Server socket has closed.'); }); }); document.getElementsByTagName('input')[0].onblur = function() { socket.send(this.value); }; </script>
复制代码
var http = require('http');
var socket = require('socket.io');
// 启http服务var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
// 监听socket链接
socket.listen(server).on('connection', function(client) {
// 接收信息
client.on('message', function(msg) {
client.send('hello:' + msg);
console.log('data from client: ---> ' + msg);
});
// 断开处理
client.on('disconnect', function() {
console.log('Client socket has closed.');
});
});
复制代码