由于同源策略的限制,满足同源的脚本才可以获取资源。虽然这样有助于保障网络安全,但另一方面也限制了资源的使用。
那么如何实现跨域呢,以下是实现跨域的一些方法。

一、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="./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="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 跨域内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax! 

js前端解决跨域的八种实现方案的更多相关文章

  1. html5 拖拽及用 js 实现拖拽功能的示例代码

    这篇文章主要介绍了html5 拖拽及用 js 实现拖拽,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  2. amaze ui 的使用详细教程

    这篇文章主要介绍了amaze ui 的使用详细教程,本文通过多种方法给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  3. swift皮筋弹动发射飞机ios源码

    这是一个款采用swift实现的皮筋弹动发射飞机游戏源码,游戏源码比较详细,大家可以研究学习一下吧。

  4. Swift与Js通过WebView交互

    开发环境:Swfit2.3XCode8.2基础概念jscontext,jscontext是代表JS的执行环境,通过-evaluateScript:方法就可以执行一JS代码JSValue,JSValue封装了JS与ObjC中的对应的类型,以及调用JS的API等JSExport,JSExport是一个协议,遵守此协议,就可以定义我们自己的协议,在协议中声明的API都会在JS中暴露出来,才能调用Swif

  5. JSCore swift

    如果双方相互引用,会造成循环引用,而导致内存泄露。以上是Jscore的基本使用,比较简单

  6. Swift WKWebView的js调用swift

    最近项目需求,需要用到JavaScriptCore和WebKit,但是网上的资源有限,而且比较杂,都是一个博客复制另外一个博客,都没有去实际敲代码验证,下面给大家分享一下我的学习过程。

  7. Swift WKWebView的swift调用js

    不多说,直接上代码:在html里面要添加的的代码,显示swift传过去的参数:这样就实现了swift给js传参数和调用!

  8. 在 Swift 專案中使用 Javascript:編寫一個將 Markdown 轉為 HTML 的編輯器

    你有強烈的好奇心,希望在你的iOS專案中使用JavaScript。jscontext中的所有值都是JSValue對象,JSValue類用於表示任意類型的JavaScript值。因此,我們既需要寫Swift代碼也要寫JavaScript代碼。此外,我們還會在JavaScript中按照這個類的定義來創建一個對象并對其屬性進行賦值。從Swift中呼叫JavaScript就如介紹中所言,JavaScriptCore中最主要的角色就是jscontext類。一個jscontext對象是位於JavaScript環境和本

  9. swift - WKWebView JS 交互

    本文介绍WKWebView怎么与js交互,至于怎么用WKWebView这里就不介绍了HTML代码APP调JS代码结果JS给APP传参数首先注册你需要监听的js方法名2.继承WKScriptMessageHandler并重写userContentController方法,在该方法里接收JS传来的参数3.结果

  10. swift 开发UIWebView跟JS的交互

    前言作为小白的我,才开始入门IOS,选择了swift来进行入门学习,学习做着公司一个简单的小小项目,该项目需要进行跟H5进行交互,然后我就开始研究了UIWebView的使用,其实基本原理跟Android的一样,因为我是Android开发的,所以就顺水推舟了。))//这里设置你需要加载的地址}overridefuncdidReceiveMemoryWarning(){super.didReceiveMemoryWarning()//disposeofanyresourcesthatcanberecreate

随机推荐

  1. js中‘!.’是什么意思

  2. Vue如何指定不编译的文件夹和favicon.ico

    这篇文章主要介绍了Vue如何指定不编译的文件夹和favicon.ico,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  3. 基于JavaScript编写一个图片转PDF转换器

    本文为大家介绍了一个简单的 JavaScript 项目,可以将图片转换为 PDF 文件。你可以从本地选择任何一张图片,只需点击一下即可将其转换为 PDF 文件,感兴趣的可以动手尝试一下

  4. jquery点赞功能实现代码 点个赞吧!

    点赞功能很多地方都会出现,如何实现爱心点赞功能,这篇文章主要为大家详细介绍了jquery点赞功能实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  5. AngularJs上传前预览图片的实例代码

    使用AngularJs进行开发,在项目中,经常会遇到上传图片后,需在一旁预览图片内容,怎么实现这样的功能呢?今天小编给大家分享AugularJs上传前预览图片的实现代码,需要的朋友参考下吧

  6. JavaScript面向对象编程入门教程

    这篇文章主要介绍了JavaScript面向对象编程的相关概念,例如类、对象、属性、方法等面向对象的术语,并以实例讲解各种术语的使用,非常好的一篇面向对象入门教程,其它语言也可以参考哦

  7. jQuery中的通配符选择器使用总结

    通配符在控制input标签时相当好用,这里简单进行了jQuery中的通配符选择器使用总结,需要的朋友可以参考下

  8. javascript 动态调整图片尺寸实现代码

    在自己的网站上更新文章时一个比较常见的问题是:文章插图太宽,使整个网页都变形了。如果对每个插图都先进行缩放再插入的话,太麻烦了。

  9. jquery ajaxfileupload异步上传插件

    这篇文章主要为大家详细介绍了jquery ajaxfileupload异步上传插件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. React学习之受控组件与数据共享实例分析

    这篇文章主要介绍了React学习之受控组件与数据共享,结合实例形式分析了React受控组件与组件间数据共享相关原理与使用技巧,需要的朋友可以参考下

返回
顶部