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

奋力向前
发布: 2021-09-06 10:16:07
转载
4248 人浏览过

之前的文章《浅析Node中zip压缩和zip解压缩(附代码)》中,给大家介绍了Node中zip压缩和zip解压缩命令的使用详解。下面本篇文章给大家了解WEB前端跨域解决方案,伙伴们来看看吧。

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

WEB前端跨域解决方案

跨域定义

广义的定义:跨域是指一个域下的文档或脚本试图去请求另一个域下的资源。

1、资源跳转: 链接、重定向、表单提交

2、资源嵌入:

登录后复制
//jquery ajax: $.ajax({ url: "http://www.chuchur.com/login", type: "get", dataType: "jsonp", // 请求方式为jsonp jsonpCallback: "test", // 自定义回调函数名 data: {}, }); //vue.js this.$http .jsonp("http://www.chuchur.com/login", { params: {}, jsonp: "test", }) .then((res) => { console.log(res); });
登录后复制

2)document.domain + iframe跨域

原理:这种方案只限于主域相同,子域不同的情况,其原理就是 两个页面通过js强制设置window.domain为主域,这样就实现了同域。

实现:

    
登录后复制

3)location.hash + iframe跨域

原理: 其原理就是通过URL传值,然后监听其hash值的变化,然后通过中间层做跳板,再利用父子窗口js parent最终来访问同域所有页面对象。

1: a.html,域2:b.html,域1:c.html

a.htmlb.html不同域只能通过hash传值通讯。

b.htmlc.html也不同域也只能单项通讯

a.htmlc.html同域,所以c.html可以通过parent来访问a.html页面对象

实现

1、a.html:(www.chuchur.com/a.html)

  `
登录后复制

2、b.html:(www.chuchur.org/b.html)

 
登录后复制

3、c.html:(www.chuchur.com/c.html)

登录后复制

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), 这个页面可以什么都不写,但是要保证能正常访问
登录后复制
 
登录后复制

5)postMessage跨域

postMessageHTML5 XMLHttpRequest Level 2中的API,可以解决以下方面的问题:

a.)页面和其打开的新窗口的数据传递

b.)多窗口之间消息传递

c.)页面与嵌套的iframe消息传递

d.)上面三个场景的跨域数据传递 用法:postMessage(data, origin)方法接受两个参数

data:html5规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用JSON.stringify()序列化。

origin:协议+主机+端口号,也可以设置为"\*",表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。

实现:

    
登录后复制

6)跨域资源共享(CORS

原理:普通跨域请求:只服务端设置Access-Control-Allow-Origin即可,前端无须设置。

cookie请求:前后端都需要设置字段,另外需注意:所带cookie为跨域请求接口所在域的cookie,而非当前页。 目前,所有浏览器都支持该功能(IE8+:IE8/9需要使用XDomainRequest对象来支持CORS),CORS也已经成为主流的跨域解决方案。

实现:

//1)原生js var xhr = new XMLHttpRequest(); // IE8/9需用window. XDomainRequest兼容 // 前端设置是否带cookie xhr.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"); //node var 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反向代理跨域

浏览器跨域访问jscssimg等常规静态资源被同源策略许可,但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(); // 前端开关:浏览器是否读写cookie xhr.withCredentials = true; // 访问nginx中的代理服务器 xhr.open('get', 'http://www.chuchur.com/?user=chuchur', true); xhr.send(); // node 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=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 protocolHTML5一种新的协议。它实现了浏览器与服务器全双工通信,同时允许跨域通讯,是server push技术的一种很好的实现。原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。

实现:

1、前端代码

user input:
登录后复制

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开发种常用的

其中第二,三、四、五种方案 ,利用ifamepostMessage则可以实现 不同窗口之间的数据通讯。

【完】

推荐学习:H5视频教程

以上是你值得了解的WEB前端跨域解决方案(代码详解)的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:chuchur.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!