电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

js前端解決跨域的八種實現方案

瀏覽:116日期:2024-04-01 11:00:37

由于同源策略的限制,滿足同源的腳本才可以獲取資源。雖然這樣有助于保障網絡安全,但另一方面也限制了資源的使用。那么如何實現跨域呢,以下是實現跨域的一些方法。

一、jsonp跨域

原理: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='http://www.hdgsjgj.cn/bcjs/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等網站是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>三、location.hash + iframe跨域

父頁面改變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='http://www.hdgsjgj.cn/bcjs/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屬性在不同的頁面(甚至不同域名)加載后依舊存在,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跨域

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 跨域內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 成都办公室装修-办公室设计-写字楼装修设计-厂房装修-四川和信建筑装饰工程有限公司 | ISO9001认证咨询_iso9001企业认证代理机构_14001|18001|16949|50430认证-艾世欧认证网 | 污水提升器,污水提升泵,污水提升装置-德国泽德(zehnder)水泵系统有限公司 | 无尘烘箱_洁净烤箱_真空无氧烤箱_半导体烤箱_电子防潮柜-深圳市怡和兴机电 | 快速门厂家-快速卷帘门-工业快速门-硬质快速门-西朗门业 | 置顶式搅拌器-优莱博化学防爆冰箱-磁驱搅拌器-天津市布鲁克科技有限公司 | 运动木地板_体育木地板_篮球馆木地板_舞台木地板-实木运动地板厂家 | 风淋室生产厂家报价_传递窗|送风口|臭氧机|FFU-山东盛之源净化设备 | 银川美容培训-美睫美甲培训-彩妆纹绣培训-新娘化妆-学化妆-宁夏倍莱妮职业技能培训学校有限公司 临时厕所租赁_玻璃钢厕所租赁_蹲式|坐式厕所出租-北京慧海通 | 存包柜厂家_电子存包柜_超市存包柜_超市电子存包柜_自动存包柜-洛阳中星 | C形臂_动态平板DR_动态平板胃肠机生产厂家制造商-普爱医疗 | 成都热收缩包装机_袖口式膜包机_高速塑封机价格_全自动封切机器_大型套膜机厂家 | SDI车窗夹力测试仪-KEMKRAFT方向盘测试仪-上海爱泽工业设备有限公司 | ISO9001认证咨询_iso9001企业认证代理机构_14001|18001|16949|50430认证-艾世欧认证网 | 天一线缆邯郸有限公司_煤矿用电缆厂家_矿用光缆厂家_矿用控制电缆_矿用通信电缆-天一线缆邯郸有限公司 | 钢绞线万能材料试验机-全自动恒应力两用机-混凝土恒应力压力试验机-北京科达京威科技发展有限公司 | 好看的韩国漫画_韩漫在线免费阅读-汗汗漫画 | 西安烟道厂家_排气道厂家_包立管厂家「陕西西安」推荐西安天宇烟道 | 上海佳武自动化科技有限公司 | 气力输送设备_料封泵_仓泵_散装机_气化板_压力释放阀-河南锐驰机械设备有限公司 | 我车网|我关心的汽车资讯_汽车图片_汽车生活!| 定制/定做冲锋衣厂家/公司-订做/订制冲锋衣价格/费用-北京圣达信 | 聚合甘油__盐城市飞龙油脂有限公司| 不锈钢水管-不锈钢燃气管-卫生级不锈钢管件-不锈钢食品级水管-广东双兴新材料集团有限公司 | 真空上料机(一种真空输送机)-百科 | DDoS安全防护官网-领先的DDoS安全防护服务商 | 粘弹体防腐胶带,聚丙烯防腐胶带-全民塑胶 | 防腐储罐_塑料储罐_PE储罐厂家_淄博富邦滚塑防腐设备科技有限公司 | 电解抛光加工_不锈钢电解抛光_常州安谱金属制品有限公司 | 棉柔巾代加工_洗脸巾oem_一次性毛巾_浴巾生产厂家-杭州禾壹卫品科技有限公司 | 石家庄救护车出租_重症转院_跨省跨境医疗转送_活动赛事医疗保障_康复出院_放弃治疗_腾康26年医疗护送转诊团队 | 珠光砂保温板-一体化保温板-有釉面发泡陶瓷保温板-杭州一体化建筑材料 | 南京试剂|化学试剂|分析试剂|实验试剂|cas号查询-专业60年试剂销售企业 | 面粉仓_储酒罐_不锈钢储酒罐厂家-泰安鑫佳机械制造有限公司 | 深圳市索富通实业有限公司-可燃气体报警器 | 可燃气体探测器 | 气体检测仪 | 青岛代理记账_青岛李沧代理记账公司_青岛崂山代理记账一个月多少钱_青岛德辉财税事务所官网 | 深圳彩钢板_彩钢瓦_岩棉板_夹芯板_防火复合彩钢板_长鑫 | FFU_空气初效|中效|高效过滤器_空调过滤网-广州梓净净化设备有限公司 | 扬尘在线监测系统_工地噪声扬尘检测仪_扬尘监测系统_贝塔射线扬尘监测设备「风途物联网科技」 | 陶瓷砂磨机,盘式砂磨机,棒销式砂磨机-无锡市少宏粉体科技有限公司 | 单级/双级旋片式真空泵厂家,2xz旋片真空泵-浙江台州求精真空泵有限公司 |