/ JavaScript  

九种实现跨域的方式

基本概念

同源策略是约定,它是浏览器最核心也最基本的安全功能。
同源:”协议+域名+端口”
img

同源策略限制内容有:

  1. Cookie、LocalStorage、IndexedDB 等存储性内容
  2. DOM 节点
  3. AJAX 请求发送后,结果被浏览器拦截了

有三个标签是允许跨域加载资源:

1
2
3
<img src=XXX>
<link href=XXX>
<script src=XXX>

跨域解决方案:

JSONP

JSONP 原理

利用 script 标签没有跨域限制的漏洞,网页可以得到从其他来源动态产生的 JSON 数据。JSONP 请求一定需要对方的服务器做支持才可以。

JSONP 优缺点

JSONP 优点是简单兼容性好,可用于解决主流浏览器的跨域数据访问的问题。缺点是仅支持 get 方法具有局限性,不安全可能会遭受 XSS 攻击。

JSONP 的实现流程

  1. 声明一个回调函数,其函数名(如 show)当做参数值,要传递给跨域请求数据的服务器,函数形参为要获取目标数据(服务器返回的 data)。
  2. 创建一个 script 标签,把那个跨域的 API 数据接口地址,赋值给 script 的 src,还要在这个地址中向服务器传递该函数名(可以通过问号传参:?callback=show)。
  3. 服务器接收到请求后,需要进行特殊的处理:把传递进来的函数名和它需要给你的数据拼接成一个字符串,例如:传递进去的函数名是 show,它准备好的数据是 show(‘我不爱你’)。
  4. 最后服务器把准备的数据通过 HTTP 协议返回给客户端,客户端再调用执行之前声明的回调函数(show),对返回的数据进行操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// index.html
function jsonp({ url, params, callback }) {
return new Promise((resolve, reject) => {
let script = document.createElement("script");
window[callback] = function(data) {
resolve(data);
document.body.removeChild(script);
};
params = { ...params, callback }; // wd=b&callback=show
let arrs = [];
for (let key in params) {
arrs.push(`${key}=${params[key]}`);
}
script.src = `${url}?${arrs.join("&")}`;
document.body.appendChild(script);
});
}
jsonp({
url: "http://localhost:3000/say",
params: { wd: "Iloveyou" },
callback: "show"
}).then(data => {
console.log(data);
});

上面这段代码相当于向http://localhost:3000/say?wd=Iloveyou&callback=show 这个地址请求数据,然后后台返回 show(‘我不爱你’),最后会运行 show()这个函数,打印出’我不爱你’

1
2
3
4
5
6
7
8
9
10
// server.js
let express = require("express");
let app = express();
app.get("/say", function(req, res) {
let { wd, callback } = req.query;
console.log(wd); // Iloveyou
console.log(callback); // show
res.end(`${callback}('我不爱你')`);
});
app.listen(3000);

cors

CORS 需要浏览器和后端同时支持。IE 8 和 9 需要通过 XDomainRequest 来实现。
浏览器会自动进行 CORS 通信,实现 CORS 通信的关键是后端。

服务端设置 Access-Control-Allow-Origin 就可以开启 CORS。 该属性表示哪些域名可以访问资源,如果设置通配符则表示所有网站都可以访问资源。

简单请求

使用方法为 GET、HEAD、POST 之一
Content-Type 的值仅限于 text/plain、multipart/form-data、application/x-www-form-urlencoded 三者之一
同时满足这两大条件,为简单请求

复杂请求

复杂请求的 CORS 请求,会在正式通信之前,增加一次 HTTP 查询请求,称为”预检”请求,该请求是 option 方法的,通过该请求来知道服务端是否允许跨域请求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// index.html
let xhr = new XMLHttpRequest();
document.cookie = "name=xiamen"; // cookie不能跨域
xhr.withCredentials = true; // 前端设置是否带cookie
xhr.open("PUT", "http://localhost:4000/getData", true);
xhr.setRequestHeader("name", "xiamen");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.response);
//得到响应头,后台需设置Access-Control-Expose-Headers
console.log(xhr.getResponseHeader("name"));
}
}
};
xhr.send();
1
2
3
4
5
//server1.js
let express = require("express");
let app = express();
app.use(express.static(__dirname));
app.listen(3000);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//server2.js
let express = require("express");
let app = express();
let whitList = ["http://localhost:3000"]; //设置白名单
app.use(function(req, res, next) {
let origin = req.headers.origin;
if (whitList.includes(origin)) {
// 设置哪个源可以访问我
res.setHeader("Access-Control-Allow-Origin", origin);
// 允许携带哪个头访问我
res.setHeader("Access-Control-Allow-Headers", "name");
// 允许哪个方法访问我
res.setHeader("Access-Control-Allow-Methods", "PUT");
// 允许携带cookie
res.setHeader("Access-Control-Allow-Credentials", true);
// 预检的存活时间
res.setHeader("Access-Control-Max-Age", 6);
// 允许返回的头
res.setHeader("Access-Control-Expose-Headers", "name");
if (req.method === "OPTIONS") {
res.end(); // OPTIONS请求不做任何处理
}
}
next();
});
app.put("/getData", function(req, res) {
console.log(req.headers);
res.setHeader("name", "jw"); //返回一个响应头,后台需设置
res.end("我不爱你");
});
app.get("/getData", function(req, res) {
console.log(req.headers);
res.end("我不爱你");
});
app.use(express.static(__dirname));
app.listen(4000);

postMessage

是为数不多可以跨域操作的 window 属性,可用于解决以下方面的问题:

  1. 页面和其打开的新窗口的数据传递
  2. 多窗口之间消息传递
  3. 页面与嵌套的 iframe 消息传递
  4. 上面三个场景的跨域数据传递
    postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。
1
otherWindow.postMessage(message, targetOrigin, [transfer]);

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// a.html
<iframe
src="http://localhost:4000/b.html"
frameborder="0"
id="frame"
onload="load()"
></iframe>
//等它加载完触发一个事件 //内嵌在http://localhost:3000/a.html
<script>
function load() {
let frame = document.getElementById("frame");
frame.contentWindow.postMessage("我爱你", "http://localhost:4000"); //发送数据
window.onmessage = function(e) {
//接受返回数据
console.log(e.data); //我不爱你
};
}
</script>
1
2
3
4
5
// b.html
window.onmessage = function(e) {
console.log(e.data); //我爱你
e.source.postMessage("我不爱你", e.origin);
};

websocket

Websocket 是 HTML5 的 WebSocket 和 HTTP 都是应用层协议,都基于 TCP 协议。但是 WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。一个持久化的协议,它实现了浏览器与服务器的全双工通信,同时也是跨域的一种解决方案。同时,WebSocket 在建立连接时需要借助 HTTP 协议,连接建立好了之后 client 与 server 之间的双向通信就与 HTTP 无关了。

1
2
3
4
5
6
7
8
9
10
// socket.html
<script>
let socket = new WebSocket("ws://localhost:3000");
socket.onopen = function() {
socket.send("我爱你"); //向服务器发送数据
};
socket.onmessage = function(e) {
console.log(e.data); //接收服务器返回的数据
};
</script>
1
2
3
4
5
6
7
8
9
10
11
// server.js
let express = require("express");
let app = express();
let WebSocket = require("ws"); //记得安装ws
let wss = new WebSocket.Server({ port: 3000 });
wss.on("connection", function(ws) {
ws.on("message", function(data) {
console.log(data);
ws.send("我不爱你");
});
});

Node 中间件代理(两次跨域)

实现原理:同源策略是浏览器需要遵循的标准,而如果是服务器向服务器请求就无需遵循同源策略。

代理服务器,需要做以下几个步骤:

  1. 接受客户端请求 。
  2. 将请求 转发给服务器。
  3. 拿到服务器 响应 数据。
  4. 将 响应 转发给客户端。

本地文件 index.html 文件,通过代理服务器http://localhost:3000向目标服务器http://localhost:4000请求数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// index.html(http://127.0.0.1:5500)
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$.ajax({
url: "http://localhost:3000",
type: "post",
data: { name: "xiamen", password: "123456" },
contentType: "application/json;charset=utf-8",
success: function(result) {
console.log(result); // {"title":"fontend","password":"123456"}
},
error: function(msg) {
console.log(msg);
}
});
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// server1.js 代理服务器(http://localhost:3000)
const http = require("http");
// 第一步:接受客户端请求
const server = http.createServer((request, response) => {
// 代理服务器,直接和浏览器直接交互,需要设置CORS 的首部字段
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers": "Content-Type"
});
// 第二步:将请求转发给服务器
const proxyRequest = http
.request(
{
host: "127.0.0.1",
port: 4000,
url: "/",
method: request.method,
headers: request.headers
},
serverResponse => {
// 第三步:收到服务器的响应
var body = "";
serverResponse.on("data", chunk => {
body += chunk;
});
serverResponse.on("end", () => {
console.log("The data is " + body);
// 第四步:将响应结果转发给浏览器
response.end(body);
});
}
)
.end();
});
server.listen(3000, () => {
console.log("The proxyServer is running at http://localhost:3000");
});
1
2
3
4
5
6
7
8
9
10
11
// server2.js(http://localhost:4000)
const http = require("http");
const data = { title: "fontend", password: "123456" };
const server = http.createServer((request, response) => {
if (request.url === "/") {
response.end(JSON.stringify(data));
}
});
server.listen(4000, () => {
console.log("The server is running at http://localhost:4000");
});

nginx 反向代理

实现原理类似于 Node 中间件代理,需要你搭建一个中转 nginx 服务器,用于转发请求。

使用 nginx 反向代理实现跨域,是最简单的跨域方式。只需要修改 nginx 的配置即可解决跨域问题,支持所有浏览器,支持 session,不需要修改任何代码,并且不会影响服务器性能。

实现思路:通过 nginx 配置一个代理服务器(域名与 domain1 相同,端口不同)做跳板机,反向代理访问 domain2 接口,并且可以顺便修改 cookie 中 domain 信息,方便当前域 cookie 写入,实现跨域登录。

先下载 nginx,然后将 nginx 目录下的 nginx.conf 修改,最后通过命令行 nginx -s reload 启动 nginx

window.name + iframe

window.name 属性的独特之处:name 值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。
其中 a.html 和 b.html 是同域的,都是http://localhost:3000;而c.html是http://localhost:4000

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// a.html(http://localhost:3000/b.html)
<iframe
src="http://localhost:4000/c.html"
frameborder="0"
onload="load()"
id="iframe"
></iframe>
<script>
let first = true;
// onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
function load() {
if (first) {
// 第1次onload(跨域页)成功后,切换到同域代理页面
let iframe = document.getElementById("iframe");
iframe.src = "http://localhost:3000/b.html";
first = false;
} else {
// 第2次onload(同域b.html页)成功后,读取同域window.name中数据
console.log(iframe.contentWindow.name);
}
}
</script>

b.html 为中间代理页,与 a.html 同域,内容为空。

1
2
3
4
// c.html(http://localhost:4000/c.html)
<script>
window.name = "我不爱你";
</script>

通过 iframe 的 src 属性由外域转向本地域,跨域数据即由 iframe 的 window.name 从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。

location.hash + iframe

实现原理: a.html 欲与 c.html 跨域相互通信,通过中间页 b.html 来实现。 三个页面,不同域之间利用 iframe 的 location.hash 传值,相同域之间直接 js 访问来通信。

具体实现步骤:一开始 a.html 给 c.html 传一个 hash 值,然后 c.html 收到 hash 值后,再把 hash 值传递给 b.html,最后 b.html 将结果放到 a.html 的 hash 值中。

1
2
3
4
5
6
7
8
// a.html
<iframe src="http://localhost:4000/c.html#iloveyou"></iframe>
<script>
window.onhashchange = function() {
//检测hash的变化
console.log(location.hash);
};
</script>
1
2
3
4
5
// b.html
<script>
window.parent.parent.location.hash = location.hash;
//b.html将结果放到a.html的hash值中,b.html可通过parent.parent访问a.html页面
</script>
1
2
3
4
5
// c.html
console.log(location.hash);
let iframe = document.createElement("iframe");
iframe.src = "http://localhost:3000/b.html#idontloveyou";
document.body.appendChild(iframe);

document.domain + iframe

该方式只能用于二级域名相同的情况下,比如 a.test.com 和 b.test.com 适用于该方式。
只需要给页面添加 document.domain =’test.com’ 表示二级域名都相同就可以实现跨域。
实现原理:两个页面都通过 js 强制设置 document.domain 为基础主域,就实现了同域。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// a.zf1.cn:3000/a.html
<body>
helloa
<iframe
src="http://b.zf1.cn:3000/b.html"
frameborder="0"
onload="load()"
id="frame"
></iframe>
<script>
document.domain = "zf1.cn";
function load() {
console.log(frame.contentWindow.a);
}
</script>
</body>
1
2
3
4
5
6
7
8
// b.zf1.cn:3000/b.html
<body>
hellob
<script>
document.domain = "zf1.cn";
var a = 100;
</script>
</body>