您好,欢迎访问一九零五行业门户网

你值得了解的WEB前端跨域解决方案(代码详解)

之前的文章《浅析node中zip压缩和zip解压缩(附代码)》中,给大家介绍了node中zip压缩和zip解压缩命令的使用详解。下面本篇文章给大家了解web前端跨域解决方案,伙伴们来看看吧。
web前端跨域解决方案
跨域定义广义的定义:跨域是指一个域下的文档或脚本试图去请求另一个域下的资源。
1、资源跳转: 链接、重定向、表单提交
2、资源嵌入:2cdf5bf648cf2f33323966d7f58a7f3f、3f1c4e4b6b16bbbd69b2ee476dc4f83a、79d7c95122630a3791db16c5259dc98d、04a0d55efbbfd646a993fbc01f262c57等dom标签,还有样式中background:url()、@font-face()等文件外链
3、脚本请求:js发起的ajax请求、dom和js对象的跨域操作等
同源策略
同源策略/sop(same origin policy)是一种约定,由netscape公司 1995 年引入浏览器,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到xss、csfr等攻击。所谓同源是指“协议+域名+端口”三者相同,即便两个不同的域名指向同一个ip地址,也非同源。
同源策略限制以下几种行为:
1、cookie、localstorage和indexdb无法读取
2、dom和js对象无法获得
3、ajax请求不能发送
跨域解决方案
1)jsonp跨域
关于jsonp的原理把握一下几点: 
1、html标签的src属性没有同源限制(支持跨域),浏览器解析script标签时,会自动下载src属性值(url)指向的资源;
2、script标签指向的资源文件被下载后,其中的内容会被立即执行;
3、服务器端的程序会解析src属性值中的url传递的参数,根据这些参数针对性返回一个/多个函数调用表达式,这些函数调用表达式的参数就是客户端跨域想得到的数据;
4、服务器生成、返回的文件中,表达式调用的函数是已经在本地提前定义好的,而参数就是希望从跨域服务器拿到的数据。字面的script标签可以,动态添加到dom树中的script也可以,后者更方便绑定事件。
5、只能实现get,也是他的弱点
实现:
// 服务端返回:test({ code: 0, message: "成功",});
<!-- 原生js --><script> var script = document.createelement("script"); script.type = "text/javascript"; // 传参并指定回调执行函数为callback script.src = "http://www.chuchur.com/login?callback=test"; document.head.appendchild(script); // 回调执行函数 function test(res) { console.log(json.stringify(res)); }</script>
//jquery ajax:$.ajax({ url: "http://www.chuchur.com/login", type: "get", datatype: "jsonp", // 请求方式为jsonp jsonpcallback: "test", // 自定义回调函数名 data: {},});//vue.jsthis.$http .jsonp("http://www.chuchur.com/login", { params: {}, jsonp: "test", }) .then((res) => { console.log(res); });
2)document.domain + iframe 跨域
原理:这种方案只限于主域相同,子域不同的情况,其原理就是 两个页面通过js强制设置window.domain为主域,这样就实现了同域。
实现:
<!-- 父窗口 https://www.chuchur.com/a.html --><iframe id="iframe" src="https://b.chuchur.com/b.html"></iframe><script> document.domain = "chuchur.com"; var user = "chuchur";</script><!-- 子窗口 https://b.chuchur.com/b.html --><script> document.domain = "chuchur.com"; // 获取父窗口中变量 alert("从父窗口取得数据" + window.parent.user);</script>
3)location.hash + iframe跨域
原理: 其原理就是通过url传值,然后监听其hash值的变化,然后通过中间层做跳板,再利用父子窗口js parent最终来访问同域所有页面对象。
域 1: a.html ,域 2:b.html ,域 1:c.html 。
a.html,b.html 不同域只能通过hash传值通讯。
b.html,c.html 也不同域也只能单项通讯
a.html,c.html 同域,所以c.html可以通过parent来访问a.html页面对象
实现:
1、a.html:(www.chuchur.com/a.html)
<iframe id="iframe" src="http://www.chuchur.org/b.html" style="display:none; "></iframe><script> var iframe = document.getelementbyid("iframe"); // 向b.html传hash值 settimeout(function () { iframe.src = iframe.src + "#nick=chuchur"; }, 1000); // 开放给同域c.html的回调方法 function test(res) { alert("数据来自c.html ---> " + res); }</script>`
2、b.html:(www.chuchur.org/b.html)
<iframe id="iframe" src="http://www.chuchur.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>
3、c.html:(www.chuchur.com/c.html)
<script> // 监听b.html传来的hash值 window.onhashchange = function () { // 再通过操作同域a.html的js回调,将结果传回 window.parent.parent.test("你好: " + location.hash.replace("#nick=", "")); };</script>
4)window.name + iframe跨域
原理:利用window.name特有属性,name值在不同的页面甚至不同域 ,当页面重新加载后依然存在,并且支持非常长的值,约 2mb。
实现:
// 1.)a.html:(www.chuchur.com/a.html)var proxy = function (url, callback) { var state = 0; var iframe = document.createelement("iframe"); // 加载跨域页面 ,先让页面的name执行赋值, iframe.src = url; // onload事件会触发2次,第1次加载跨域页,并留存数据于window.name iframe.onload = function () { if (state === 1) { // 第2次onload(同域proxy页)成功后,读取同域window.name中数据 test(iframe.contentwindow.name); destoryframe(); } else if (state === 0) { // 第1次onload(跨域页)成功后,切换到同域代理页面 iframe.contentwindow.location = "http://www.chuchur.com/b.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.chuchur.com/proxy.html), 这个页面可以什么都不写,但是要保证能正常访问
<!-- 3.)b.html:(www.chuchur.org/b.html) --><script> window.name = "我是一个可以非常长的变量";</script>
5)postmessage跨域
postmessage是html5 xmlhttprequest level 2中的api,可以解决以下方面的问题:
a.)页面和其打开的新窗口的数据传递
b.)多窗口之间消息传递
c.)页面与嵌套的iframe消息传递
d.)上面三个场景的跨域数据传递用法:postmessage(data, origin)方法接受两个参数
data:html5规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用json.stringify()序列化。
origin: 协议+主机+端口号,也可以设置为"\*",表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。
实现:
<!-- 1.)a.html:(www.chuchur.com/a.html) --><iframe id="iframe" src="http://www.chuchur.com/b.html" style="display:none; "></iframe><script> var iframe = document.getelementbyid("iframe"); iframe.onload = function () { var data = { name: "邱秋", }; // 向chuchur.org传送跨域数据 iframe.contentwindow.postmessage( json.stringify(data), "http://www.chuchur.org" ); }; // 接受chuchur.org返回数据 window.addeventlistener( "message", function (e) { alert("我来自chuchur.org: " + e.data); }, false );</script><!-- 2.)b.html:(www.chuchur.org/b.html) --><script> // 接收chuchur.com的数据 window.addeventlistener( "message", function (e) { alert("我来自chuchur.com " + e.data); var data = json.parse(e.data); if (data) { data.nick = chuchur; // 处理后再发回chuchur.com window.parent.postmessage( json.stringify(data), "http://www.chuchur.org" ); } }, false );</script>
6)跨域资源共享(cors)
原理:普通跨域请求:只服务端设置access-control-allow-origin即可,前端无须设置。
带cookie请求:前后端都需要设置字段,另外需注意:所带cookie为跨域请求接口所在域的cookie,而非当前页。 目前,所有浏览器都支持该功能(ie8+:ie8/9需要使用xdomainrequest对象来支持cors),cors也已经成为主流的跨域解决方案。
实现:
//1)原生jsvar xhr = new xmlhttprequest(); // ie8/9需用window. xdomainrequest兼容// 前端设置是否带cookiexhr.withcredentials = true;xhr.open('post', 'http://www.chuchur.com/login', true);xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded');xhr.send('user=chuchur');xhr.onreadystatechange = function() { if (xhr.readystate == 4 && xhr.status == 200) { alert(xhr.responsetext); }};//2.)jquery ajax$.ajax({ ... xhrfields: { withcredentials: true // 前端设置是否带cookie }, crossdomain: true, // 会让请求头中包含跨域的额外信息,但不会含cookie ...});//3.)vue框架在vue-resource封装的ajax组件中加入以下代码:vue.http.options.credentials = true//后台服务端//java/* * 导入包:import javax.servlet.http. httpservletresponse; * 接口参数中定义:httpservletresponse response */response.setheader("access-control-allow-origin", "http://www.chuchur.com"); // 若有端口需写全(协议+域名+端口)response.setheader("access-control-allow-credentials", "true");//nodevar server = http.createserver();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.chuchur.com', // 允许访问的域(协议+域名+端口) 'set-cookie': 'l=abcdef; path=/; domain=www.chuchur.com; httponly' // httponly: 脚本无法读取cookie }); res.write(json.stringify(postdata)); res.end(); });});server.listen('3000');
7)nginx反向代理跨域
浏览器跨域访问js、css、img等常规静态资源被同源策略许可,但iconfont字体文件(eot|otf|ttf|woff|svg)例外,此时可在nginx的静态资源服务器中加入以下配置。
location / { add_header access-control-allow-origin *; }
原理:通过nginx代理一个 同域不同端口的跳板机,反向代理要跨域的域名,这样可以修改cookie里面的domain信息实现跨域
实现:
#nginx具体配置:server { listen 80; server_name www.chuchur.com; location / { proxy_pass http://www.chuchur.org; #反向代理 proxy_cookie_domain www.chuchur.org www.chuchur.com; #修改cookie里域名 index index.html index.htm; # 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用 add_header access-control-allow-origin http://www.chuchur.com; #当前端只跨域不带cookie时,可为* add_header access-control-allow-credentials true; }}
前端实现
var xhr = new xmlhttprequest();// 前端开关:浏览器是否读写cookiexhr.withcredentials = true;// 访问nginx中的代理服务器xhr.open('get', 'http://www.chuchur.com/?user=chuchur', true);xhr.send();// nodevar 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=abcdef; path=/; domain=www.chuchur.org; httponly' // httponly: 脚本无法读取 }); res.write(json.stringify(params)); res.end();});server.listen('8080');
8)nodejs中间件代理跨域
原理同nignx代理跨域类似,都是通过代理服务器实现数据转发
实现:
//1)利用中间件http-proxy-middleware实现var express = require('express');var proxy = require('http-proxy-middleware');var app = express();app.use('/', proxy({ // 代理跨域目标接口 target: 'http://www.chuchur.org:', changeorigin: true, // 修改响应头信息,实现跨域并允许带cookie onproxyres: function(proxyres, req, res) { res.header('access-control-allow-origin', 'http://www.chuchur.com'); res.header('access-control-allow-credentials', 'true'); }, // 修改响应信息中的cookie域名 cookiedomainrewrite: 'www.chuchur.com' // 可以为false,表示不修改}));app.listen(3000);//2)利用中间件 webpack-dev-server实现//webpack.config.js部分配置:module.exports = { entry: {}, module: {}, ... devserver: { historyapifallback: true, proxy: [{ context: '/login', target: 'http://www.chuchur.org', // 代理跨域目标接口 changeorigin: true, cookiedomainrewrite: 'www.chuchur.com' // 可以为false,表示不修改 }], noinfo: true }}
9)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.chuchur.org"); // 连接成功处理 socket.on("connect", function () { // 监听服务端消息 socket.on("message", function (msg) { console.log("来自服务器的消息: " + msg); }); // 监听服务端关闭 socket.on("disconnect", function () { console.log("server socket has closed."); }); }); document.getelementsbytagname("input")[0].onblur = function () { socket.send(this.value); };</script>
2、nodejs socket后台:
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('哈哈:' + msg); console.log('来自客服端的消息': -- - > ' + msg); }); // 断开处理 client.on('disconnect', function() { console.log('client socket has closed.'); }); });
以上 9 种方式都能实现跨域数据传递,用的最多的还是第六种跨域资源共享(cors),在前后端分离开发模式最常见。第七种和第八种中间件代理实现方式则是在基于node开发种常用的
其中第二,三、四、五种方案 ,利用ifame和postmessage则可以实现 不同窗口之间的数据通讯。
【完】
推荐学习:h5视频教程
以上就是你值得了解的web前端跨域解决方案(代码详解)的详细内容。
其它类似信息

推荐信息