1. 什么是跨域

什么是同源?

:::info 同源就是协议(http or https)+域名(baidu.com or juejin.com)+端口号(80 or 3000)相同,然后只要有任何的两个地址有其中一项不相同,都会出现跨域情况。注意对于跨域浏览器很直接是对于url的首部进行这三项的判断,即使你是同一个ip的同端口协议,域名不同,也是跨域 :::

同源策略的限制内容:

  • cookie,localStorage,
  • dom节点
  • ajax请求返回的结果

    允许跨域加载资源的内容:

  • 跨域解决方案大全(具体) - 图1

  • 跨域之后请求究竟发出去没有

    :::info 跨域之后请求的确是发出去了,而且服务器也接收到了,并且也返回了结果,只不过浏览器的返回的结果给拦截掉了;如果你疑问为什么表单发请求不会跨域,ajax就会,因为表单根本就是只发请求,没有处理接收服务器返回的结果;跨域归根到底是为了阻止用户读取到不同源的内容 :::

2. 解决办法

方法1:jsonp

优点

  • 简单兼容性好

    缺点

  • 只支持get方法

  • 不安全,可能会遭受xss攻击

    代码实现

    ```html <!DOCTYPE html>

    i am h1

  1. ```javascript
  2. const express = require('express');
  3. const app = express();
  4. app.get('/go', (req, res) => {
  5. const fn = req.query.callback; // myCallBack
  6. res.end(`${fn}('我是jsonp')`)
  7. })
  8. app.listen('8888', () => {
  9. console.log('启动监听');
  10. })

方法2:cors

特点

  • 需要浏览器和后端同时支持
  • IE 8 和 9 需要通过 XDomainRequest 来实现

    实现

  • 设置 Access-Control-Allow-Origin 就可以开启cors,表示什么域名可以访问资源,如果设置通配符则都可以

    代码实现

    ```javascript // 前端发送ajax请求
    let xhr;

    1. window.XMLHttpRequest ? xhr = new XMLHttpRequest() : xhr = new ActiveXObject(); // 兼容ie5,6
    2. xhr.open('POST','http://localhost:8888/back',true); // 发送请求
    3. xhr.setRequestHeader('Content-type', "application/x-www-form-urlencoded"); // 设置请求头,post请求需要设置
    4. xhr.send('test=cindy'); // 发送数据给后端
    5. xhr.onreadystatechange = function () { // 监听状态的变化
    6. if (xhr.readyState === 4 && xhr.status === 200) {
    7. console.log(xhr.responseText); // {"name":"joe"}
    8. }
    9. }

// 后端接收请求设置cors跨域 const express = require(‘express’); const app = express(); app.all(‘‘, (req, res, next) => { //所有请求都进来设置以下跨域 res.header(“Access-Control-Allow-Origin”, ““); // 核心 res.header(“Access-Control-Allow-Methods”, “GET,HEAD,OPTIONS,POST,PUT”); res.header(“Access-Control-Allow-Headers”, “Origin, X-Requested-With, Content-Type, Accept, Authorization”); next(); }) app.post(‘/back’, (req, res) => { const result = {name: ‘joe’}; res.json(result) }) app.listen(‘8888’, () => { console.log(‘启动监听’); })

  1. <a name="wTiBb"></a>
  2. ### 方法3:postMessage
  3. <a name="rnbL2"></a>
  4. #### 特点
  5. - 允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。
  6. <a name="ihSOB"></a>
  7. #### 主要场景
  8. - 页面和其打开的新窗口的数据传递
  9. - 多窗口之间消息传递
  10. - 页面与嵌套的iframe消息传递
  11. - 上面三个场景的跨域数据传递
  12. <a name="IqzXs"></a>
  13. #### 上代码
  14. ```javascript
  15. // 文件 http://localhost:63342/node/index.html
  16. <h1 onclick="emit()">index11.html</h1>
  17. <iframe src="http://localhost:8081"></iframe>
  18. <script>
  19. function emit () {
  20. window.frames[0].postMessage("test", '*');
  21. }
  22. window.addEventListener('message', (event) => {
  23. console.log('接收到回复:' + event.data); // 接收到回复:test ok
  24. })
  25. </script>
  26. // 文件 http://localhost:8081
  27. mounted() {
  28. window.addEventListener('message', (event) => {
  29. console.log('接收到:', event.data); // 接收到:test
  30. });
  31. window.parent.postMessage('test ok');
  32. },
  33. };

方法4:webscoket

特点

  • HTML5的一个持久化的协议
  • 实现了浏览器与服务器的全双工通信
  • WebSocket和HTTP都是应用层协议,都基于 TCP 协
  • WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据

    上代码

    ```javascript // idnex.html let socket = new WebSocket(‘ws://localhost:3000’); socket.onopen = function () { socket.send(‘我爱你’);//向服务器发送数据 } socket.onmessage = function (e) { console.log(e.data);//接收服务器返回的数据 }

// ws.js let WebSocket = require(‘ws’);//记得安装ws let wss = new WebSocket.Server({port:3000}); wss.on(‘connection’,function(ws) { ws.on(‘message’, function (data) { console.log(JSON.stringify(data)); ws.send(‘我不爱你’) }); })

  1. <a name="SDNRM"></a>
  2. ### 方法5:nginx反向代理
  3. - 使用nginx反向代理实现跨域,是最简单的跨域方式。
  4. - 只需要修改nginx的配置即可解决跨域问题,支持所有浏览器,支持session,不需要修改任何代码,并且不会影响服务器性能。
  5. <a name="aMntH"></a>
  6. ### 方法6:window.name+iframe
  7. <a name="KNvsA"></a>
  8. #### 原理
  9. - window.name属性的独特之处:name值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。·
  10. <a name="Gqnk5"></a>
  11. #### 上代码
  12. ```html
  13. a.html // 3000端口
  14. b.html // 3000端口
  15. c.html // 4000端口
  16. // a.html
  17. <iframe onload='onload' src='http://localhost:4000/c.html'></iframe>
  18. <script>
  19. let first = true;
  20. function load() {
  21. if (first) {
  22. let iframe = document.getElementById('iframe');
  23. iframe.src = 'http://localhost:3000/b.html';
  24. } else {
  25. console.log(iframe.contentWindow.name); // 测试通过
  26. }
  27. }
  28. </script>
  29. // c.html
  30. <script>
  31. window.name = '测试通过'
  32. </script>
  33. // 先引入不同源的c页面,c页面设置的name以及缓存着了,然后把iframe替换程同源的b页面,这个时候name这个缓存不会消失,间接就获取到了
  34. iframe

方法7:location.hash+iframe

原理

  • 利用一个中间的的同源的b.html页面,让a.html和c.html来通信,通过iframe的嵌套和hash的传递

    上代码

    ```html // a.html

    // b.html

    // c.html console.log(location.hash); // aPageInfomation let iframe = document.createElement(‘iframe’); iframe.src = ‘http://localhost:3000/b.html#cPageInfomation‘; document.body.appendChild(iframe);

  1. <a name="x0l5V"></a>
  2. ### 方法8:document.domain+iframe
  3. <a name="Ir2UK"></a>
  4. #### 原理
  5. - 该方式只能用于二级域名相同的情况下
  6. - 只需要给页面添加,document.domain='主域名'
  7. - 两个页面都通过js强制设置document.domain为基础主域,就实现了同域。
  8. <a name="kzgWo"></a>
  9. #### 上代码
  10. ```html
  11. // a.html
  12. <body>
  13. helloa
  14. <iframe src="http://buhuidadaima.com:3000/b.html" onload="load()" id="frame"></iframe>
  15. <script>
  16. document.domain = 'buhuidadaima.com'
  17. function load() {
  18. console.log(frame.contentWindow.a);
  19. }
  20. </script>
  21. </body>
  22. // b.html
  23. <body>
  24. hellob
  25. <script>
  26. document.domain = 'buhuidadaima.com'
  27. var a = 100;
  28. </script>
  29. </body>