本文详细解析前端解决跨域的八种常见方案,包括JSONP、document.domain、location.hash、window.name、postMessage、CORS、WebSocket及Nginx反向代理。涵盖原理、适用场景及代码实现,帮助开发者根据实际需求选择最优跨域策略。
受同源策略约束,只有满足同源条件的脚本才能访问资源。尽管这一机制有助于维护网络安全,但也对资源的获取造成了一定限制。
一、JSONP跨域
核心原理:script标签引入外部JavaScript文件时不受跨域限制。此外,所有带有src属性的HTML标签均不受同源策略影响。
利用这一特性,我们可以通过script标签的src属性加载远程资源,并将数据以JSON格式存放于src指向的服务器端。
由于无法直接判断script标签src的加载状态,我们需预先定义回调函数。服务端会在返回数据前拼接该函数名,待资源加载完成后自动调用此函数,并将后端返回的数据作为参数传入。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
function callback(data) {
alert(data.test);
}
</script>
<script src="./jsonp.js"></script>
</body>
</html>
jsonp.js
callback({"test": 0});
访问index.html后,弹窗将显示0。该方案的局限性在于仅支持GET请求。
二、document.domain结合iframe跨域
此方案仅适用于主域名相同但子域名不同的场景。
例如,百度的主网站为www.baidu.com,而zhidao.baidu.com和news.baidu.com等均为该主域下的子域。
实现方式:两个页面均通过JavaScript将document.domain设置为基础主域,从而使其处于同域状态,实现资源互操作。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<iframe src="https://mfaying.github.io/lesson/cross-origin/document-domain/child.html"></iframe>
<script>
document.domain = 'mfaying.github.io';
var t = '0';
</script>
</body>
</html>
child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
document.domain = 'mfaying.github.io';
alert(window.parent.t);
</script>
</body>
</html>
三、location.hash结合iframe跨域
父页面修改iframe的src属性,导致location.hash值变化,此过程不会刷新页面(仍为同一页面)。子页面可通过window.location.hash获取传递的值。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<iframe src="child.html#" style="display: none;"></iframe>
<script>
var oIf = document.getElementsByTagName('iframe')[0];
document.addEventListener('click', function () {
oIf.src += '0';
}, false);
</script>
</body>
</html>
child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
window.onhashchange = function() {
alert(window.location.hash.slice(1));
}
</script>
</body>
</html>
点击index.html页面后,弹窗将显示0。
四、window.name结合iframe跨域
原理:window.name属性在页面加载后(即使跨域)依然保留,且可存储较长数据(约2MB)。在非同源iframe中设置window.name后,将其指向同源页面,此时window.name值保持不变,从而实现跨域数据获取。
./parent/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var oIf = document.createElement('iframe');
oIf.src = 'https://mfaying.github.io/lesson/cross-origin/window-name/child.html';
var state = 0;
oIf.onload = function () {
if (state === 0) {
state = 1;
oIf.src = 'https://mfaying.github.io/lesson/cross-origin/window-name/parent/proxy.html';
} else {
alert(JSON.parse(oIf.contentWindow.name).test);
}
}
document.body.appendChild(oIf);
</script>
</body>
</html>
./parent/proxy.html
空文件,仅作为代理页面使用。
./child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
window.name = '{"test": 0}'
</script>
</body>
</html>
五、postMessage跨域
postMessage是HTML5引入的跨文档消息传输机制。用法:getMessageHTML.postMessage(data, origin)。其中,data为HTML5规范支持的基本类型或可复制对象,但部分浏览器仅支持字符串,建议传输时使用JSON.stringify()进行序列化。
origin指定协议、主机及端口号,也可设为"*"以允许传递给任意窗口;若需指定同源,则设置为"/"。getMessageHTML为接收信息页面的引用,可以是iframe的contentWindow属性、window.open的返回值,或通过name/下标从window.frames获取的值。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<iframe id='ifr' src='./child.html' style="display: none;"></iframe>
<button id='btn'>click</button>
<script>
var btn = document.getElementById('btn');
btn.addEventListener('click', function () {
var ifr = document.getElementById('ifr');
ifr.contentWindow.postMessage(0, '*');
}, false);
</script>
</body>
</html>
child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
window.addEventListener('message', function(event){
alert(event.data);
}, false);
</script>
</body>
</html>
点击index.html页面上的按钮,弹窗将显示0。
六、跨域资源共享(CORS)
只需在服务端设置Access-Control-Allow-Origin即可实现跨域请求;若涉及Cookie,前后端均需进行相应设置。受同源策略影响,读取的Cookie为跨域请求接口所在域的Cookie,而非当前页面Cookie。CORS是目前主流的跨域解决方案。
原生Node.js实现
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</head>
<body>
<script>
$.get('http://localhost:8080', function (data) {
alert(data);
});
</script>
</body>
</html>
server.js
var http = require('http');
var server = http.createServer();
server.on('request', function(req, res) {
res.writeHead(200, {
'Access-Control-Allow-Credentials': 'true', // 后端允许发送Cookie
'Access-Control-Allow-Origin': 'https://mfaying.github.io', // 允许访问的域(协议+域名+端口)
'Set-Cookie': 'key=1;Path=/;Domain=mfaying.github.io;HttpOnly' // HttpOnly:脚本无法读取cookie
});
res.write(JSON.stringify(req.method));
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
Koa结合koa2-cors中间件实现
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
</head>
<body>
<script>
$.get('http://localhost:8080', function (data) {
alert(data);
});
</script>
</body>
</html>
server.js
var koa = require('koa');
var router = require('koa-router')();
const cors = require('koa2-cors');
var app = new koa();
app.use(cors({
origin: function (ctx) {
if (ctx.url === '/test') {
return false;
}
return '*';
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
router.get('/', async function (ctx) {
ctx.body = "0";
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
console.log('server is listening in port 3000');
七、WebSocket协议跨域
WebSocket是HTML5定义的新协议,支持浏览器与服务器间的全双工通信,并允许跨域,是服务端推送技术的优秀实现方式。
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
var ws = new WebSocket('ws://localhost:8080/', 'echo-protocol');
// 建立连接触发的事件
ws.onopen = function () {
var data = { "test": 1 };
ws.send(JSON.stringify(data));// 可以给后台发送数据
};
// 接收到消息的回调方法
ws.onmessage = function (event) {
alert(JSON.parse(event.data).test);
}
// 断开连接触发的事件
ws.onclose = function () {
conosle.log('close');
};
</script>
</body>
</html>
server.js
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log('Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log('Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('echo-protocol', request.origin);
console.log('Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
const reqData = JSON.parse(message.utf8Data);
reqData.test -= 1;
connection.sendUTF(JSON.stringify(reqData));
}
});
connection.on('close', function() {
console.log('close');
});
});
八、Nginx代理跨域
原理:同源策略是浏览器的安全机制,并非HTTP协议的一部分。服务器端调用HTTP接口时仅使用HTTP协议,不存在跨域问题。
实现方式:通过Nginx配置代理服务器(域名与test1相同,端口不同)作为跳板机,反向代理访问test2接口,并可修改Cookie中的test信息,便于当前域Cookie写入,实现跨域登录。Nginx具体配置如下:
#proxy服务器
server {
listen 81;
server_name www.test1.com;
location / {
proxy_pass http://www.test2.com:8080; #反向代理
proxy_cookie_test www.test2.com www.test1.com; #修改cookie里域名
index index.html index.htm;
add_header Access-Control-Allow-Origin http://www.test1.com; #当前端只跨域不带cookie时,可为*
add_header Access-Control-Allow-Credentials true;
}
}
至此,关于JS前端解决跨域的八种实现方案介绍完毕。如需了解更多JS跨域相关内容,请搜索本站历史文章或继续浏览下方相关文章,感谢大家的支持!