1. 什么是跨域
什么是同源?
:::info 同源就是协议(http or https)+域名(baidu.com or juejin.com)+端口号(80 or 3000)相同,然后只要有任何的两个地址有其中一项不相同,都会出现跨域情况。注意对于跨域浏览器很直接是对于url的首部进行这三项的判断,即使你是同一个ip的同端口协议,域名不同,也是跨域 :::
同源策略的限制内容:
- cookie,localStorage,
- dom节点
-
允许跨域加载资源的内容:
-
跨域之后请求究竟发出去没有
:::info 跨域之后请求的确是发出去了,而且服务器也接收到了,并且也返回了结果,只不过浏览器的返回的结果给拦截掉了;如果你疑问为什么表单发请求不会跨域,ajax就会,因为表单根本就是只发请求,没有处理接收服务器返回的结果;跨域归根到底是为了阻止用户读取到不同源的内容 :::
2. 解决办法
方法1:jsonp
优点
```javascriptconst express = require('express');const app = express();app.get('/go', (req, res) => {const fn = req.query.callback; // myCallBackres.end(`${fn}('我是jsonp')`)})app.listen('8888', () => {console.log('启动监听');})
方法2:cors
特点
- 需要浏览器和后端同时支持
IE 8 和 9 需要通过 XDomainRequest 来实现
实现
设置 Access-Control-Allow-Origin 就可以开启cors,表示什么域名可以访问资源,如果设置通配符则都可以
代码实现
```javascript // 前端发送ajax请求
let xhr;window.XMLHttpRequest ? xhr = new XMLHttpRequest() : xhr = new ActiveXObject(); // 兼容ie5,6xhr.open('POST','http://localhost:8888/back',true); // 发送请求xhr.setRequestHeader('Content-type', "application/x-www-form-urlencoded"); // 设置请求头,post请求需要设置xhr.send('test=cindy'); // 发送数据给后端xhr.onreadystatechange = function () { // 监听状态的变化if (xhr.readyState === 4 && xhr.status === 200) {console.log(xhr.responseText); // {"name":"joe"}}}
// 后端接收请求设置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(‘启动监听’); })
<a name="wTiBb"></a>### 方法3:postMessage<a name="rnbL2"></a>#### 特点- 允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。<a name="ihSOB"></a>#### 主要场景- 页面和其打开的新窗口的数据传递- 多窗口之间消息传递- 页面与嵌套的iframe消息传递- 上面三个场景的跨域数据传递<a name="IqzXs"></a>#### 上代码```javascript// 文件 http://localhost:63342/node/index.html<h1 onclick="emit()">index11.html</h1><iframe src="http://localhost:8081"></iframe><script>function emit () {window.frames[0].postMessage("test", '*');}window.addEventListener('message', (event) => {console.log('接收到回复:' + event.data); // 接收到回复:test ok})</script>// 文件 http://localhost:8081mounted() {window.addEventListener('message', (event) => {console.log('接收到:', event.data); // 接收到:test});window.parent.postMessage('test ok');},};
方法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(‘我不爱你’) }); })
<a name="SDNRM"></a>### 方法5:nginx反向代理- 使用nginx反向代理实现跨域,是最简单的跨域方式。- 只需要修改nginx的配置即可解决跨域问题,支持所有浏览器,支持session,不需要修改任何代码,并且不会影响服务器性能。<a name="aMntH"></a>### 方法6:window.name+iframe<a name="KNvsA"></a>#### 原理- window.name属性的独特之处:name值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。·<a name="Gqnk5"></a>#### 上代码```htmla.html // 3000端口b.html // 3000端口c.html // 4000端口// a.html<iframe onload='onload' src='http://localhost:4000/c.html'></iframe><script>let first = true;function load() {if (first) {let iframe = document.getElementById('iframe');iframe.src = 'http://localhost:3000/b.html';} else {console.log(iframe.contentWindow.name); // 测试通过}}</script>// c.html<script>window.name = '测试通过'</script>// 先引入不同源的c页面,c页面设置的name以及缓存着了,然后把iframe替换程同源的b页面,这个时候name这个缓存不会消失,间接就获取到了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);
<a name="x0l5V"></a>### 方法8:document.domain+iframe<a name="Ir2UK"></a>#### 原理- 该方式只能用于二级域名相同的情况下- 只需要给页面添加,document.domain='主域名'- 两个页面都通过js强制设置document.domain为基础主域,就实现了同域。<a name="kzgWo"></a>#### 上代码```html// a.html<body>helloa<iframe src="http://buhuidadaima.com:3000/b.html" onload="load()" id="frame"></iframe><script>document.domain = 'buhuidadaima.com'function load() {console.log(frame.contentWindow.a);}</script></body>// b.html<body>hellob<script>document.domain = 'buhuidadaima.com'var a = 100;</script></body>
