之前的文章《浅析Node中zip压缩和zip解压缩(附代码)》中,给大家介绍了Node中zip压缩和zip解压缩命令的使用详解。下面本篇文章给大家了解WEB前端跨域解决方案,伙伴们来看看吧。
WEB前端跨域解决方案 跨域定义广义的定义:跨域是指一个域下的文档或脚本试图去请求另一个域下的资源。 1、资源跳转: 链接、重定向、表单提交 2、资源嵌入: 3、脚本请求: 同源策略同源策略 同源策略限制以下几种行为:1、 2、 3、 跨域解决方案
关于 1、 2、 3、服务器端的程序会解析 4、服务器生成、返回的文件中,表达式调用的函数是已经在本地提前定义好的,而参数就是希望从跨域服务器拿到的数据。字面的 5、只能实现 实现: // 服务端返回: 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.js this.$http .jsonp("http://www.chuchur.com/login", { params: {}, jsonp: "test", }) .then((res) => { console.log(res); }); 2) 原理:这种方案只限于主域相同,子域不同的情况,其原理就是 两个页面通过 实现: <!-- 父窗口 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) 原理: 其原理就是通过 域
实现: 1、 <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、 <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、 <script> // 监听b.html传来的hash值 window.onhashchange = function () { // 再通过操作同域a.html的js回调,将结果传回 window.parent.parent.test("你好: " + location.hash.replace("#nick=", "")); }; </script> 4) 原理:利用 实现: // 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)
实现: <!-- 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)跨域资源共享( 原理:普通跨域请求:只服务端设置 带 实现: //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) 浏览器跨域访问 location / { add_header Access-Control-Allow-Origin *; } 原理:通过 实现: #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) 原理同 实现: //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)
实现: 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、 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 种方式都能实现跨域数据传递,用的最多的还是第六种跨域资源共享( 其中第二,三、四、五种方案 ,利用 【完】 推荐学习:H5视频教程 以上就是你值得了解的WEB前端跨域解决方案(代码详解)的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |