1. 什么是跨域?
- 当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。
2. 为什么会出现跨域问题
- 出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)
3. 非同源限制
- 无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB
- 无法接触非同源网页的 DOM
- 无法向非同源地址发送 AJAX 请求
4. 跨域的十种解决方法
4.1 设置document.domain + iframe解决无法读取非同源网页的 Cookie问题
- 因为浏览器是通过document.domain属性来检查两个页面是否同源,因此只要通过设置相同的document.domain,两个页面就可以共享Cookie(此方案仅限主域相同,子域不同的跨域应用场景。)
- 实现原理:两个页面都通过js强制设置document.domain为基础主域,就实现了同域。
- 父窗口:(http://www.domain.com/a.html)
1 2 3 4 5
| <iframe id="iframe" src="http://child.domain.com/b.html"></iframe> <script> document.domain = 'domain.com'; var user = 'admin'; </script>
|
- 子窗口:(http://child.domain.com/b.html)
1 2 3 4 5
| <script> document.domain = 'domain.com'; alert('get js data from parent ---> ' + window.parent.user); </script>
|
4.2 location.hash + iframe跨域
- 实现原理: a欲与b跨域相互通信,通过中间页c来实现。 三个页面,不同域之间利用iframe的location.hash传值,相同域之间直接js访问来通信。
- 具体实现:A域:a.html -> B域:b.html -> A域:c.html,a与b不同域只能通过hash值单向通信,b与c也不同域也只能单向通信,但c与a同域,所以c可通过parent.parent访问a页面所有对象。
- a.html:(http://www.domain1.com/a.html)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe> <script> var iframe = document.getElementById('iframe');
setTimeout(function() { iframe.src = iframe.src + '#user=admin'; }, 1000); function onCallback(res) { alert('data from c.html ---> ' + res); } </script>
|
- b.html:(http://www.domain2.com/b.html)
1 2 3 4 5 6 7 8 9
| <iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe> <script> var iframe = document.getElementById('iframe');
window.onhashchange = function () { iframe.src = iframe.src + location.hash; }; </script>
|
- c.html:(http://www.domain1.com/c.html)
1 2 3 4 5 6 7
| <script> window.onhashchange = function () { window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', '')); }; </script>
|
- window.name属性的独特之处:name值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。
- a.html:(http://www.domain1.com/a.html)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| if (state === 1) { callback(iframe.contentWindow.name); destoryFrame();
} else if (state === 0) { iframe.contentWindow.location = 'http://www.domain1.com/proxy.html'; state = 1; } };
document.body.appendChild(iframe);
function destoryFrame() { iframe.contentWindow.document.write(''); iframe.contentWindow.close(); document.body.removeChild(iframe); } };
proxy('http://www.domain2.com/b.html', function(data){ alert(data); });
|
-
proxy.html:(http://www.domain1.com/proxy…
中间代理页,与a.html同域,内容为空即可。
-
b.html:(http://www.domain2.com/b.html)
1 2 3
| <script> window.name = 'This is domain2 data!'; </script>
|
- 总结:通过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。
4.4 跨文档通信 API:window.postMessage()
调用postMessage方法实现父窗口http://test1.com向子窗口http://test2.com发消息(子窗口同样可以通过该方法发送消息给父窗口);它可用于解决以下方面的问题:
- 页面和其打开的新窗口的数据传递
- 多窗口之间消息传递
- 页面与嵌套的iframe消息传递
- 上面三个场景的跨域数据传递
用法:postMessage(data,origin)方法接受两个参数
data: html5规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用JSON.stringify()序列化。
origin: 协议+主机+端口号,也可以设置为"*“,表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为”/"。
- a.html:(http://www.domain1.com/a.html)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe> <script> var iframe = document.getElementById('iframe'); iframe.onload = function() { var data = { name: 'aym' }; iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com'); };
window.addEventListener('message', function(e) { alert('data from domain2 ---> ' + e.data); }, false); </script>
|
- b.html:(http://www.domain2.com/b.html)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <script> window.addEventListener('message', function(e) { alert('data from domain1 ---> ' + e.data);
var data = JSON.parse(e.data); if (data) { data.number = 16;
window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com'); } }, false); </script>
|
4.5 JSONP
- JSONP 是服务器与客户端跨源通信的常用方法。最大特点就是简单适用,兼容性好(兼容低版本IE),缺点是只支持get请求,不支持post请求。
- 核心思想:网页通过添加一个
<script>元素,向服务器请求 JSON 数据,服务器收到请求后,将数据放在一个指定名字的回调函数的参数位置传回来。
- 通常为了减轻web服务器的负载,我们把js、css,img等静态资源分离到另一台独立域名的服务器上,在html页面中再通过相应的标签从不同域名下加载静态资源,而被浏览器允许,基于此原理,我们可以通过动态创建script,再请求一个带参网址实现跨域通信。
- jsonp缺点:只能实现get一种请求。
【1】原生实现:
1 2 3 4 5 6 7 8 9 10
| <script src="http://test.com/data.php?callback=dosomething"></script>
<script type="text/javascript"> function dosomething(res){ console.log(res.data) } </script>
|
【2】jQuery ajax:
1 2 3 4 5 6 7
| $.ajax({ url: 'http://www.test.com:8080/login', type: 'get', dataType: 'jsonp', jsonpCallback: "handleCallback", data: {} });
|
【3】Vue.js
1 2 3 4 5 6
| this.$http.jsonp('http://www.domain2.com:8080/login', { params: {}, jsonp: 'handleCallback' }).then((res) => { console.log(res); })
|
后端node.js代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| var querystring = require('querystring'); var http = require('http'); var server = http.createServer();
server.on('request', function(req, res) { var params = qs.parse(req.url.split('?')[1]); var fn = params.callback;
res.writeHead(200, { 'Content-Type': 'text/javascript' }); res.write(fn + '(' + JSON.stringify(params) + ')');
res.end(); });
server.listen('8080'); console.log('Server is running at port 8080...');
|
4.6 CORS
CORS 是跨域资源分享(Cross-Origin Resource Sharing)的缩写。它是 W3C 标准,属于跨源 AJAX 请求的根本解决方法。
1、普通跨域请求:只需服务器端设置Access-Control-Allow-Origin
2、带cookie跨域请求:前后端都需要进行设置
- 【前端设置】根据xhr.withCredentials字段判断是否带有cookie
【1】原生ajax
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| var xhr = new XMLHttpRequest();
xhr.withCredentials = true; xhr.open('post', 'http://www.domain2.com:8080/login', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('user=admin'); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); } };
|
【2】jQuery ajax
1 2 3 4 5 6 7 8 9
| $.ajax({ url: 'http://www.test.com:8080/login', type: 'get', data: {}, xhrFields: { withCredentials: true }, crossDomain: true, });
|
【3】vue-resource
1
| Vue.http.options.credentials = true
|
【4】axios
1
| axios.defaults.withCredentials = true
|
- 【服务端设置】
服务器端对于CORS的支持,主要是通过设置Access-Control-Allow-Origin来进行的。如果浏览器检测到相应的设置,就可以允许Ajax进行跨域的访问。
【1】Java后台
1 2 3 4 5 6 7 8 9 10 11 12 13
|
response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
|
【2】Nodejs后台
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| var http = require('http'); var server = http.createServer(); var qs = require('querystring'); server.on('request', function(req, res) { var postData = ''; req.addListener('data', function(chunk) { postData += chunk; }); req.addListener('end', function() { postData = qs.parse(postData); res.writeHead(200, { 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': 'http://www.domain1.com',
'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' }); res.write(JSON.stringify(postData)); res.end(); }); }); server.listen('8080'); console.log('Server is running at port 8080...');
|
【3】PHP后台
1 2
| <?php header("Access-Control-Allow-Origin:*");
|
【4】Apache需要使用mod_headers模块来激活HTTP头的设置,它默认是激活的。你只需要在Apache配置文件的, , 或的配置里加入以下内容即可
1
| Header set Access-Control-Allow-Origin *
|
4.7 webpack本地代理
在vue.config.js中利用 WebpackDevServer 配置本地代理
案例:
http://localhost:8080/api/v2/tv/modules?for_mobile=1
https://m.douban.com/rexxar/api/v2/tv/modules?for_mobile=1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <template> <div id="app"> </div> </template>
<script> import axios from 'axios' export default { name: 'App', data(){ return {
} }, mounted() { axios.get('api/v2/tv/modules?for_mobile=1').then(res => { console.log(res) }) }, methods:{ } } </script>
<style scoped> </style>
|
vue.config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, devServer: { proxy: { '/api': { target: 'https://m.douban.com/rexxar/api/', changeOrigin: true, pathRewrite:{ '^/api':'' } }, } } })
|
4.8 WebSocket协议跨域
- WebSocket protocol是HTML5一种新的协议。它实现了浏览器与服务器全双工通信,同时允许跨域通讯,是server push技术的一种很好的实现。
- 原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。
- 前端代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| <div>user input:<input type="text"></div> <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script> <script> var socket = io('http://www.domain2.com:8080');
socket.on('connect', function() { socket.on('message', function(msg) { console.log('data from server: ---> ' + msg); });
socket.on('disconnect', function() { console.log('Server socket has closed.'); }); });
document.getElementsByTagName('input')[0].onblur = function() { socket.send(this.value); }; </script>
|
- Nodejs socket后台:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| var http = require('http'); var socket = require('socket.io');
var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); res.end(); });
server.listen('8080'); console.log('Server is running at port 8080...');
socket.listen(server).on('connection', function(client) { client.on('message', function(msg) { client.send('hello:' + msg); console.log('data from client: ---> ' + msg); });
client.on('disconnect', function() { console.log('Client socket has closed.'); }); });
|
4.9 Nginx反向代理
-
Nginx 实现原理类似于 Node 中间件代理,需要你搭建一个中转 nginx 服务器,用于转发请求。
-
使用 nginx 反向代理实现跨域,是最简单的跨域方式。只需要修改 nginx 的配置即可解决跨域问题,支持所有浏览器,支持 session,不需要修改任何代码,并且不会影响服务器性能。
-
我们只需要配置nginx,在一个服务器上配置多个前缀来转发http/https请求到多个真实的服务器即可。这样,这个服务器上所有url都是相同的域 名、协议和端口。因此,对于浏览器来说,这些url都是同源的,没有跨域限制。而实际上,这些url实际上由物理服务器提供服务。这些服务器内的 javascript可以跨域调用所有这些服务器上的url。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #proxy服务器 server { listen 81; 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; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| server { #nginx监听所有localhost:8080端口收到的请求 listen 8080; server_name localhost; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; #localhost:8080 会被转发到这里 #同时, 后端程序会接收到 "192.168.25.20:8088"这样的请求url location / { proxy_pass http://192.168.25.20:8088; } #localhost:8080/api/ 会被转发到这里 #同时, 后端程序会接收到 "192.168.25.20:9000/api/"这样的请求url location /api/ { proxy_pass http://192.168.25.20:9000; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }
|
- 前端代码示例:
1 2 3 4 5 6 7 8
| var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('get', 'http://www.domain1.com:81/?user=admin', true); xhr.send();
|
- Nodejs后台示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 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));
res.writeHead(200, { 'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' });
res.write(JSON.stringify(params)); res.end(); });
server.listen('8080'); console.log('Server is running at port 8080...');
|
4.10 Nodejs中间件代理跨域
- node中间件实现跨域代理,原理大致与nginx相同,都是通过启一个代理服务器,实现数据的转发,也可以通过设置cookieDomainRewrite参数修改响应头中cookie中域名,实现当前域的cookie写入,方便接口登录认证。
- 非vue框架的跨域(2次跨域)
利用node + express + http-proxy-middleware搭建一个proxy服务器。
【1】前端代码示例:
1 2 3 4 5 6 7 8
| var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('get', 'http://www.domain1.com:3000/login?user=admin', true); xhr.send();
|
【2】中间件服务器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var express = require('express'); var proxy = require('http-proxy-middleware'); var app = express();
app.use('/', proxy({ target: 'http://www.domain2.com:8080', changeOrigin: true,
onProxyRes: function(proxyRes, req, res) { res.header('Access-Control-Allow-Origin', 'http://www.domain1.com'); res.header('Access-Control-Allow-Credentials', 'true'); },
cookieDomainRewrite: 'www.domain1.com' }));
app.listen(3000); console.log('Proxy server is listen at port 3000...');
|
【3】Nodejs后台同(4.9 Nginx反向代理)
- vue框架的跨域(1次跨域)
利用node + webpack + webpack-dev-server代理接口跨域。在开发环境下,由于vue渲染服务和接口代理服务都是webpack-dev-server同一个,所以页面与代理接口之间不再跨域,无须设置headers跨域信息了。
webpack.config.js部分配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| module.exports = { entry: {}, module: {}, ... devServer: { historyApiFallback: true, proxy: [{ context: '/login', target: 'http://www.domain2.com:8080', changeOrigin: true, secure: false, cookieDomainRewrite: 'www.domain1.com' }], noInfo: true } }
|
5. 总结
- CORS支持所有类型的HTTP请求,是跨域HTTP请求的根本解决方案
- JSONP只支持GET请求,JSONP的优势在于支持老式浏览器,以及可以向不支持CORS的网站请求数据。
- 不管是Node中间件代理还是nginx反向代理,主要是通过同源策略对服务器不加限制。
- 日常工作中,用得比较多的跨域方案是cors和nginx反向代理