栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

JavaScript 九种跨域方式实现原理

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript 九种跨域方式实现原理

前言

前后端数据交互经常会碰到请求跨域,什么是跨域,以及有哪几种跨域方式,这是本文要探讨的内容。

一、什么是跨域?

1.什么是同源策略及其限制内容?

同源策略是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,浏览器很容易受到 XSS、CSFR 等攻击。所谓同源是指"协议+域名+端口"三者相同,即便两个不同的域名指向同一个 ip 地址,也非同源。

同源策略限制内容有:

  • cookie、LocalStorage、IndexedDB 等存储性内容
  • DOM 节点
  • AJAX 请求发送后,结果被浏览器拦截了

但是有三个标签是允许跨域加载资源:

  • // b.html
     window.onmessage = function(e) {
     console.log(e.data) //我爱你
     e.source.postMessage('我不爱你', e.origin)
     }
    

    4.websocket

    Websocket 是 HTML5 的一个持久化的协议,它实现了浏览器与服务器的全双工通信,同时也是跨域的一种解决方案。WebSocket 和 HTTP 都是应用层协议,都基于 TCP 协议。但是 WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。同时,WebSocket 在建立连接时需要借助 HTTP 协议,连接建立好了之后 client 与 server 之间的双向通信就与 HTTP 无关了。

    原生 WebSocket API 使用起来不太方便,我们使用Socket.io,它很好地封装了 webSocket 接口,提供了更简单、灵活的接口,也对不支持 webSocket 的浏览器提供了向下兼容。

    我们先来看个例子:本地文件 socket.html 向localhost:3000发生数据和接受数据

    // socket.html
    
    
    // server.js
    let express = require('express');
    let app = express();
    let WebSocket = require('ws');//记得安装ws
    let wss = new WebSocket.Server({port:3000});
    wss.on('connection',function(ws) {
     ws.on('message', function (data) {
     console.log(data);
     ws.send('我不爱你')
     });
    })
    

    5. Node 中间件代理(两次跨域)

    实现原理:同源策略是浏览器需要遵循的标准,而如果是服务器向服务器请求就无需遵循同源策略。
    代理服务器,需要做以下几个步骤:

    • 接受客户端请求 。
    • 将请求 转发给服务器。
    • 拿到服务器 响应 数据。
    • 将 响应 转发给客户端。

    我们先来看个例子:本地文件 index.html 文件,通过代理服务器http://localhost:3000向目标服务器http://localhost:4000请求数据。

    // index.html(http://127.0.0.1:5500)
     
     
    // server1.js 代理服务器(http://localhost:3000)
    const http = require('http')
    // 第一步:接受客户端请求
    const server = http.createServer((request, response) ={
     // 代理服务器,直接和浏览器直接交互,需要设置CORS 的首部字段
     response.writeHead(200, {
     'Access-Control-Allow-Origin': '*',
     'Access-Control-Allow-Methods': '*',
     'Access-Control-Allow-Headers': 'Content-Type'
     })
     // 第二步:将请求转发给服务器
     const proxyRequest = http
     .request(
      {
      host: '127.0.0.1',
      port: 4000,
      url: '/',
      method: request.method,
      headers: request.headers
      },
      serverResponse ={
      // 第三步:收到服务器的响应
      var body = ''
      serverResponse.on('data', chunk ={
       body += chunk
      })
      serverResponse.on('end', () ={
       console.log('The data is ' + body)
       // 第四步:将响应结果转发给浏览器
       response.end(body)
      })
      }
     )
     .end()
    })
    server.listen(3000, () ={
     console.log('The proxyServer is running at http://localhost:3000')
    })
    // server2.js(http://localhost:4000)
    const http = require('http')
    const data = { title: 'fontend', password: '123456' }
    const server = http.createServer((request, response) ={
     if (request.url === '/') {
     response.end(JSON.stringify(data))
     }
    })
    server.listen(4000, () ={
     console.log('The server is running at http://localhost:4000')
    })
    

    上述代码经过两次跨域,值得注意的是浏览器向代理服务器发送请求,也遵循同源策略,最后在 index.html 文件打印出{"title":"fontend","password":"123456"}

    6.nginx 反向代理

    实现原理类似于 Node 中间件代理,需要你搭建一个中转 nginx 服务器,用于转发请求。

    使用 nginx 反向代理实现跨域,是最简单的跨域方式。只需要修改 nginx 的配置即可解决跨域问题,支持所有浏览器,支持 session,不需要修改任何代码,并且不会影响服务器性能。

    实现思路:通过 nginx 配置一个代理服务器(域名与 domain1 相同,端口不同)做跳板机,反向代理访问 domain2 接口,并且可以顺便修改 cookie 中 domain 信息,方便当前域 cookie 写入,实现跨域登录。

    先下载nginx,然后将 nginx 目录下的 nginx.conf 修改如下:

    // proxy服务器
    server {
     listen  80;
     server_name www.domain1.com;
     location / {
      proxy_pass http://www.domain2.com:8080; #反向代理
      proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名
      index index.html index.htm;
    
      # 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用
      add_header Access-Control-Allow-Origin http://www.domain1.com; #当前端只跨域不带cookie时,可为*
      add_header Access-Control-Allow-Credentials true;
     }
    }
    
    

    最后通过命令行nginx -s reload启动 nginx

    // index.html
    var xhr = new XMLHttpRequest();
    // 前端开关:浏览器是否读写cookie
    xhr.withCredentials = true;
    // 访问nginx中的代理服务器
    xhr.open('get', 'http://www.domain1.com:81/?user=admin', true);
    xhr.send();
    
    // server.js
    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=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly:脚本无法读取
     });
     res.write(JSON.stringify(params));
     res.end();
    });
    server.listen('8080');
    console.log('Server is running at port 8080...');
    

    7.window.name + iframe

    window.name 属性的独特之处:name 值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。

    其中 a.html 和 b.html 是同域的,都是http://localhost:3000;而 c.html 是http://localhost:4000

     // a.html(http://localhost:3000/b.html)
     
     

    b.html 为中间代理页,与 a.html 同域,内容为空。

     // c.html(http://localhost:4000/c.html)
     

    总结:通过 iframe 的 src 属性由外域转向本地域,跨域数据即由 iframe 的 window.name 从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。

    8.location.hash + iframe

    实现原理: a.html 欲与 c.html 跨域相互通信,通过中间页 b.html 来实现。 三个页面,不同域之间利用 iframe 的 location.hash 传值,相同域之间直接 js 访问来通信。

    具体实现步骤:一开始 a.html 给 c.html 传一个 hash 值,然后 c.html 收到 hash 值后,再把 hash 值传递给 b.html,最后 b.html 将结果放到 a.html 的 hash 值中。

    同样的,a.html 和 b.html 是同域的,都是http://localhost:3000;而 c.html 是http://localhost:4000

     // a.html
     
     
    
    
    
     // b.html
     
     // c.html
     console.log(location.hash);
     let iframe = document.createElement('iframe');
     iframe.src = 'http://localhost:3000/b.html#idontloveyou';
     document.body.appendChild(iframe);
    9.document.domain + iframe

    该方式只能用于二级域名相同的情况下,比如 a.test.com 和 b.test.com 适用于该方式。
    只需要给页面添加 document.domain ='test.com' 表示二级域名都相同就可以实现跨域。

    实现原理:两个页面都通过 js 强制设置 document.domain 为基础主域,就实现了同域。

    我们看个例子:页面a.zf1.cn:3000/a.html获取页面b.zf1.cn:3000/b.html中 a 的值

    // a.html
    
     helloa
     
     
    
    
    // b.html
    
     hellob
     
    
    

    三、总结

    CORS 支持所有类型的 HTTP 请求,是跨域 HTTP 请求的根本解决方案

    JSONP 只支持 GET 请求,JSONP 的优势在于支持老式浏览器,以及可以向不支持 CORS 的网站请求数据。

    不管是 Node 中间件代理还是 nginx 反向代理,主要是通过同源策略对服务器不加限制。

    日常工作中,用得比较多的跨域方案是 cors 和 nginx 反向代理

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/77221.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号