js是如何实现跨域的?教你八种方式
Admin 2021-10-21 群英技术资讯 1427 次浏览
本文给大家分享是的JS跨域的内容,由于同源策略的限制,满足同源的脚本才可以获取资源。虽然这样有助于保障网络安全,但另一方面也限制了资源的使用。那么js是如何实现跨域的呢?接下来给大家分享八种方式实现跨域的方案。
原理:script标签引入js文件不受跨域影响。不仅如此,带src属性的标签都不受同源策略的影响。
正是基于这个特性,我们通过script标签的src属性加载资源,数据放在src属性指向的服务器上,使用json格式。
由于我们无法判断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一种请求。
此方案仅限主域相同,子域不同的应用场景。
比如百度的主网页是www.baidu.com,zhidao.baidu.com、news.baidu.com等网站是www.baidu.com这个主域下的子域。
实现原理:两个页面都通过js设置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>
父页面改变iframe的src属性,location.hash的值改变,不会刷新页面(还是同一个页面),在子页面可以通过window.localtion.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属性在不同的页面(甚至不同域名)加载后依旧存在,name可赋较长的值(2MB)。
在iframe非同源的页面下设置了window的name属性,再将iframe指向同源的页面,此时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是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。
只要在服务端设置Access-Control-Allow-Origin就可以实现跨域请求,若是cookie请求,前后端都需要设置。
由于同源策略的限制,所读取的cookie为跨域请求接口所在域的cookie,并非当前页的cookie。
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 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...');
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协议是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');
});
});
原理:同源策略是浏览器的安全策略,不是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跨域的内容,大家可以关注其它的相关文章。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
在制作网页页面时,轮播图效果是比较常见的,想要实现轮播图效果的方法很多,本文主要介绍的使用jQuery实现轮播图,以下是实现代码,感兴趣的朋友可以了解看看。
我们知道jquery中的组件有很多,但是也有可能找不到符合我们需求的组件,我们就可以自己封装一个组件。在JQ中,是允许我们自定义一些插件与扩展的。呢么jquery自定义组件的方法是什么呢?其实,定义的方式也比较简单,采用$.extend就行,那么下面就来看看在JQ中自定义一个插件的实例。
sockjs-node报错是啥原因?sockjs-node接口报错的原因有很多,可能是热加载功能失效,还可能是shadowsock代理、nodejs配置等等,要解决保持的问题,先判断出原因很重要的。针对下文的情况,我们来看看是什么原因及如何解决。
在使用react-router-dom在编写项目的时候有种感觉就是,使用起来非常的方便,但是若是维护起来,那便是比较麻烦了,因为各大路由分散在各个组件中. 所以我们就会想到,使用react-router-dom中提供的config模式来编写我们的路由,这样写的好处就是我们可以将逻辑集中在一处,配置路由比较方便
这篇文章主要给大家分享vue实现点击切换图片效果的内容,切换图片的效果在很多网站上都是比较常见的,小编觉得比较实用,因此分享给大家做个参考,感兴趣的朋友可以看看,希望大家阅读完这篇文章能有所收获,下面我们一起来学习一下吧。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008