不为人知的跨域解决方式

1,432 阅读5分钟

前言

前后端数据交互经常会碰到请求跨域,什么是跨域,还有跨域有几种解决方式呢?下面让我们来一一探讨。

一.什么是跨域?产生的原因是什么呢?

为什么会产生跨域呢,因为浏览器为了安全采用了一系列的安全机制,其中有一个是同源策略。何为同源策略(same-origin policy)。简单来讲同源策略就是浏览器为了保证用户信息的安全,防止恶意的网站窃取数据,禁止不同域之间的JS进行交互。对于浏览器而言只要域名、协议、端口其中一个不同就会引发同源策略。

同源策略有哪些限制呢?

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

但是浏览器有三种标签让我们支持跨域的

  • <img />
  • <script />
  • <link />

二.跨域解决方式

1.jsonp

1.jsonp原理

利用 <script> 标签没有跨域限制的优势,网页可以得到从其他来源动态产生的 JSON 数据。JSONP请求一定需要对方的服务器做对接才可以。
  • 声明一个回调函数,其函数名(如sayHello)当做参数值,要传递给跨域请求数据的服务器,函数形参为要获取目标数据(服务器返回的data)。

  • 创建一个 script标签,把那个跨域的API数据接口地址,赋值给script的src,还要在这个地址中向服务器传递该函数名(可以通过问号传参:?callback=sayHello)。

  • 服务器接收到请求后,需要进行特殊的处理:把传递进来的函数名和它需要给你的数据拼接成一个字符串,例如:传递进去的函数名是sayHello,它准备好的数据是sayHello('吃饭了吗')。

  • 最后服务器把准备的数据通过HTTP协议返回给客户端,客户端再调用执行之前声明的回调函数(sayHello),对返回的数据进行操作。

2.jsonp优缺点

JSONP优点是简单兼容性好,可用于解决主流浏览器的跨域数据访问的问题。缺点是仅支持get方法具有局限性,不安全可能会遭受XSS攻击。

  // index.html
  <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jsonp</title>
</head>

<body>
    <script>
        function jsonp({ url, params, cb }) {
            return new Promise((resolve, reject) => {
                let script = document.createElement('script');
                window[cb] = function (data) {
                    resolve(data);
                    document.body.removeChild(script);
                }
                params = { ...params, cb }; //  把params转换成wd=b&cb=sayHello这种格式
                let arrs = [];
                for (let key in params) {
                    arrs.push(`${key}=${params[key]}`);
                }
                script.src = `${url}?${arrs.join('&')}`;
                document.body.appendChild(script);
            })
        }

        //  封装自己的jsonp函数
        //  jsonp缺点:只能发送get请求,不支持post put delete方法,不安全,xss攻击
        jsonp({
            url: 'http://localhost:8888/hello',
            params: { wd: '你好呀' },
            cb: 'sayHello'
        }).then(res => {
            console.log(res)
        })
    </script>
</body>
</html>
//  server.js
  let express = require('express');
  let app = express();

  app.get('/hello',function (req,res) {
    let {wd,cb} = req.query;
    console.log(wd); 
    res.end(`${cb}('吃饭了吗')`) 
  })
  app.listen(8888);

2.cors

原理

CORS是跨源AJAX请求的根本解决方法。JSONP只能发GET请求,但是CORS允许任何类型的请求。

整个CORS通信过程都是浏览器自动完成的,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多一次附加的请求,但用户不会有感觉。因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。

  //  index.html
  <!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>
    let xhr = new XMLHttpRequest;
    document.cookie = 'name=xht';
    xhr.withCredentials = true;
    xhr.open('PUT','http://localhost:4000/getData',true);
    xhr.setRequestHeader('name','zfpx');
    xhr.onreadystatechange = function () {
      if(xhr.readyState === 4){
        if(xhr.status>=200 && xhr.status < 300 || xhr.status ===304){
          console.log(xhr.response);
          console.log(xhr.getResponseHeader('name'));
        }
      }
    }
    xhr.send();
  </script>
</body>
</html>
  // server1.js
  let express = require('express');
  let app = express();
  app.use(express.static(__dirname));
  app.listen(3000);
  //  server2.js
  let express = require('express');
let app = express();
let whitList = ['http://localhost:3000']
app.use(function (req,res,next) {
  let origin = req.headers.origin;
  if(whitList.includes(origin)){
    // 设置哪个源可以访问我
    res.setHeader('Access-Control-Allow-Origin', origin);
    // 允许携带哪个头访问我
    res.setHeader('Access-Control-Allow-Headers','name');
    // 允许哪个方法访问我
    res.setHeader('Access-Control-Allow-Methods','PUT');
    // 允许携带cookie
    res.setHeader('Access-Control-Allow-Credentials', true);
    // 预检的存活时间
    res.setHeader('Access-Control-Max-Age',6);
    // 允许返回的头
    res.setHeader('Access-Control-Expose-Headers', 'name');
    if(req.method === 'OPTIONS'){
      res.end(); // OPTIONS请求不做任何处理
    }
  }
  next();
});
app.put('/getData', function (req, res) {
  console.log(req.headers);
  res.setHeader('name','jw');
  res.end("我不爱你")
})
app.get('/getData',function (req,res) {
  console.log(req.headers);
  res.end("我不爱你")
})
app.use(express.static(__dirname));
app.listen(4000);

3.postMessage

postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。它可以解决传递数据的情况有下面几种

  • 页面和其打开的新窗口的数据传递
  • 多窗口之间消息传递
  • 页面与嵌套的iframe消息传递
  • 上面三个场景的跨域数据传递

接下来我们看个例子: http://localhost:3000/a.html页面向http://localhost:4000/b.html传递“我爱你”,然后后者传回"我不爱你"。

  //  a.html
  <!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>
  a.html
  <iframe src="http://localhost:4000/b.html" frameborder="0" id="frame" onload="load()"></iframe>
  <script>
    function load() {
      let frame = document.getElementById('frame');
      frame.contentWindow.postMessage('我爱你','http://localhost:4000');
      window.onmessage = function (e) {
        console.log(e.data,'b页面发回来的数据');
      }
    }
  </script>
</body>
</html>
  //  b.html
  <!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>
    window.onmessage = function (e) {
      console.log(e.data,'a页面发过来的数据');
      e.source.postMessage('我不爱你',e.origin)
    }
  </script>
</body>
</html>

4.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)
  <iframe src="http://localhost:4000/c.html" frameborder="0" onload="load()" id="iframe"></iframe>
  <script>
    let first = true
    // onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
    function load() {
      if(first){
      // 第1次onload(跨域页)成功后,切换到同域代理页面
        let iframe = document.getElementById('iframe');
        iframe.src = 'http://localhost:3000/b.html';
        first = false;
      }else{
      // 第2次onload(同域b.html页)成功后,读取同域window.name中数据
        console.log(iframe.contentWindow.name);
      }
    }
  </script>

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

// c.html(http://localhost:4000/c.html)
  <script>
    window.name = '我不爱你'  
  </script>  

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

5.document.domain + iframe

该方式只能用于二级域名相同的情况下,比如 a.xht.com 和 b.xht.com 适用于该方式。 只需要给页面添加 document.domain ='xht.com' 表示二级域名都相同就可以实现跨域。 实现原理:两个页面都通过js强制设置document.domain为基础主域,就实现了同域。 我们看个例子:页面a.xht.com:3000/a.html获取页面b.xht.com:3000/b.html中a的值

  // a.html
<body>
 helloa
  <iframe src="http://b.xht.com:3000/b.html" frameborder="0" onload="load()" id="frame"></iframe>
  <script>
    document.domain = 'xht.com'
    function load() {
      console.log(frame.contentWindow.a);
    }
  </script>
</body>

  // b.html
<body>
   hellob
   <script>
     document.domain = 'xht.com'
     var a = 100;
   </script>
</body>

6.websocket

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

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

 // socket.html
<script>
   let socket = new WebSocket('ws://localhost:3000');
   socket.onopen = function () {
     socket.send('我爱你');//向服务器发送数据
   }
   socket.onmessage = function (e) {
     console.log(e.data);//接收服务器返回的数据
   }
</script>
 // 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('我不爱你')
 });
})

7.location.hash + iframe

实现原理:a给c传一个hash值 c收到hash值后 c把hash值传递给b b将结果放到a的hash值中, a.html和b.html是同域的,都是http://localhost:3000;而c.html是http://localhost:4000

   // a.html
  <iframe src="http://localhost:4000/c.html#iloveyou"></iframe>
  <script>
    window.onhashchange = function () { //检测hash的变化
      console.log(location.hash);
    }
  </script>

   // b.html
  <script>
    window.parent.parent.location.hash = location.hash 
    //b.html将结果放到a.html的hash值中,b.html可通过parent.parent访问a.html页面
  </script>
  // c.html
 console.log(location.hash);
  let iframe = document.createElement('iframe');
  iframe.src = 'http://localhost:3000/b.html#idontloveyou';
  document.body.appendChild(iframe); 

8.nginx

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

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

3.总结

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

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

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

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