前言
跨域对于前端来说绝对是一个熟悉的词,在实际的项目中遇到也会经常遇到,但是跨域的解决方法多种多样,所以就来总结一下基本的跨域方法。
什么是跨域
跨域一词从字面上来看就是跨域名,但实际上跨域名并不是理解的那么狭隘,其实际上只要是协议、域名、端口有任何一个不同,都会被当做是不同的域。之所以会存在跨域的问题,主要是为了保障浏览器的安全,但是这也对前端的工作造成了不少的麻烦,所以我们要通过一些方法使本域的 js 能够操作其它域的页面对象或者使其它域的 js 能操作本域的页面对象,介绍具体方法之前先说明一下到底什么算是同域
跨域解决方案
通过 jsonp 跨域
通常为了减轻 web 服务器的负载,我们会把 js、css、img 等静态资源分离到另一台独立域名的服务器上,在 html 页面中再通过相应的标签从不同域名下加载静态资源,这是被浏览器所允许的,借助此原理,我们可以通过动态创建 script,再请求一个带参数的网址实现跨域通信。
(1) 原生实现
<script>
var script = document.createElement('script');
script.type = 'text/javascript';
// 传参并指定回调函数 onBack
script.src = 'http://www.domain.com:8080/login?user=admin&callback=onBack';
document.head.appendChild(script);
// 执行回调函数
function onBack(res){
alert(JSON.stringify(res));
};
</script>
服务端返回如下
onBack({"status":true,"user":"admin"});
(2) jquery ajax
$.ajax({
url:'http://www.domian.com:8080/login',
type:'get',
dataType:'jsonp', // 请求方式为 jsonp
jsonpCallback:'onBack', // 自定义回调函数名
data:{}
});
(3) vue
this.$http.jsonp('http://www.domian.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();
sever.on('request',function(req.res){
var params = qs.parse(req.url.split('?')[1]);
var fn = params.callback;
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 请求
通过 document.domain + iframe 跨域
注:此方案仅限于主域相同,子域不同的应用场景(我几乎没用过)
实现原理:两个页面都通过 js 强制设置 document.domain 为基础主域,就实现同域
(1) 父窗口(www.domain.com/b.html)
<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
document.domain = "domain.com";
var user = "admin";
</script>
(2) 子窗口(child.domain.com/b.html)
<script>
document.domain = "domain.com";
console.log("get js data from parent --->" + window.parent.user);
</scrip>
通过 location.hash + iframe 跨域
实现原理:a 欲与 b 跨域相互通信,可以通过中间页 c 来实现。三个页面,不同域之间利用 iframe 的 location.hash 传值,相同域之间直接访问 js 来进行同行。
具体实现:A 域:a.html -> B 域:b.html -> A 域:c.html ,a 与 b 不同域只能使用 hash 值进行单向通信,b 与 c 也不同域所以也只能通过 hash 值单向通信,但是 c 与 a 同域可以通过 parent.parent 访问 a 的所有内容。
(1) 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 = admian";
},1000);
// 开放给 c.html 的回调方法
function callBack(res){
alert("data from c.html" + res);
};
</script>
(2) b.html(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 传来的 hash 值之后将其传给 c
window.onhashchange = function () {
iframe.src = iframe.src + location.hash;
};
</script>
(3) c.html(www.domain1.com/c.html)
<script>
window.onhashchange = function(){
window.parent.parent.callBack("hello" + location.hash.replace("#user=",""));
};
</script>
通过 window.name + iframe 跨域
window.name 属性的独特之处在于:name 值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)
(1) a.html(www.domain1.com/a.html)
<script>
var proxy = function(url,callback){
var state = 0;
var iframe = document.createElement('iframe');
// 加载跨域页面
iframe.src = url;
// onload 事件会触发 2 次,第一次加载跨域页,并留存数据于 window.name
iframe.onload = function(){
if(state == 1){
// 第二次 onload(同域 proxy 页)成功后,读取同域 window.name 中数据
callback(iframe.contentWindow.name);
destoryFrame();
}else if(state == 0){
// 第一次 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(www.domain1.com/proxy.html)
中间代理页,与 a.html 同域,内容为空即可
(3) b.html(www.domain2.com/b.html)
<script>
window.name = "This is domain2 data!";
</script>
通过 postMessage 跨域
postMessage 是 HTML5 XMLHttpRequest Level 2 中的 API,且是为数不多的可以进行跨域操作的 window 属性之一,它可用于解决以下方面的问题:
a、页面和其打开的新窗口的数据传递
b、多窗口之间的数据传递
c、页面与嵌套的 iframe 消息的传递
d、上面三个场景的跨域数据传递
用法:postMessage(data,origin) 方法接受两个参数。
data:HTML5 规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用 JSON.stringify() 序列化。
origin:协议 + 主机 + 端口号,也可以设置为"*",表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。
(1) a.html(www.domain1.com/a.html)
<iframe id="iframe" src="http://www.domain2.com/b.html" style="dispaly: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");
};
window.addEventListener('message',function(e){
alert('data from domain2'+e.data)
},false);
</script>
(2) b.html(www.domain2.com/b.html)
<script>
window.addEventListener('message',function(e){
alert('data from domain1' + e.data);
var data = JSON.parse(e.data);
if(data){
data.number = 10;
// 处理后在发回给 domain1
window.parent.postMessage(JSON.stringify(data),'http://www.domain1.com');
};
},false);
</script>
跨域资源共享 (CORS)
普通跨域请求:只服务端设置 Access-Control-Allow-Origin 即可,前端无需设置。
带 cookie 请求:前后端都需要设置字段,另外需要注意,所带的 cookie 为跨域请求接口所在域的 cookie,而非当前页。
目前,所有浏览器都支持该功能(IE8+:IE8/9 需要使用 XDomainRequest 对象来支持 CORS),CORS 也已经成为主流的跨域解决方案。
(1) 前端设置
原生 ajax
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-from-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;
(2) 服务端设置
Nodejs 后台设置
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-Orign':'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....');
nginx 代理跨域
nginx 配置解决 iconfont 跨域
浏览器跨域访问 js、css、img 等常规静态资源被同源策略许可,但 iconfont 字体文件(eot|otf|ttf|woff|svg) 例外,此时可在 nginx 的静态资源服务器中加入以下配置。
location / {
add_header Access-Control-Allow-Origin * ;
}
nginx 反向代理接口跨域
跨域原理:同源策略是浏览器的安全策略,不是 HTTP 协议的一部分。服务器端调用 HTTP 接口只是使用 HTTP 协议,不会执行 JS 脚本,不需要同源策略,也就不存在跨域问题。
实现思路:通过 nginx 配置一个代理服务器(域名与 domain1 相同,端口不同)做跳板机,反向代理访问 domain2 接口,并且可以顺便修改 cookie 中的 domain 信息,方便当前域 cookie 写入,实现跨域登录。
(1) nginx 具体配置
proxy 服务器
server {
listen 81;
server_name www.domain1.com;
location / {
proxy_pass http://www.domain2.com:8080; # 反向代理
proxy_cookie_domian www.domain2.com www.domain1.com; # 修改 cookie 中的域名
index index.html index.htm;
# 当用 webpack-dev-server 等中间件代理接口访问 nginx 时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不用
add_header Access-Control-Allow-Origin http://www.domain1.com; # 当前端只跨域不带 cookie 时,可为 *
add_header Access-Control-Allow-Credentials true;
}
}
前端代码示例
var xhr = new XMLHttpRequest();
// 前端开关:浏览器是否读写 cookie
xhr.withCreadentiials = true;
// 访问 nginx 中的代理服务器
xhr.open('get','http://www.domain1.com:81/?user=admin',true);
xhr.send();
Nodejs 后台示例
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...')
Nodejs 中间件代理跨域
node 中间件实现跨域代理,原理大致与 nginx 相同,都是通过设置一个代理服务器,去实现数据的转发。
非 vue 框架的跨域(2次跨域)
利用 node + express + http-proxy-middleware 搭建一个 proxy 服务器。
(1) 前端代码示例
var xhr = new XMLHttpRequest();
// 前端开关:浏览器是否读写 cookie
xhr.withCredentials = true;
// 访问 http-proxy-middleware 代理服务器
xhr.open('get','http://domain1.com:3000/login?user=admin',true);
xhr.send();
(2) 中间件服务器
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....');
(3) 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 协议跨域
WebSocket protocol 是 HTML5 的一种新的协议。它实现了浏览器与服务器全双工通信,同时允许跨域通讯,是 server push 技术的一种很好的实现。原生 WebSocket API 使用起来不太方便,我们可以使用 Socket.io,它很好的封装了 WebSocket 接口,提供了更简单、灵活的接口,也对不支持 WebSocket 的浏览器提供了向下兼容。
(1) 前端代码
<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(){
scoket.send(this.value);
};
</script>
(2) Nodejs scoket 后台
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');
});
})