同源策略
协议 域名 端口 这三个一致就是同域
http://www.aa.cn:8081
https://www.bb.cn:8082
为什么浏览器不支持跨域
cookie localStorage这些都是同域下的,不支持跨域
DOM元素也也有同源策略 iframe
ajax 也不支持跨域
实现跨域(期望两个页面见可以实现通信 怎么弄???)
1、jsonp
2、cors(后端提供)
3、postMessage (两个页面间的通信)
4、document.domain
5、window.name
6、location.hash(哈希)
7、http-proxy
8、nginx
9、websocket
1、jsonp
三种方式不受同源策略的影响
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<title>Document</title>
<!-- <link ref="stylesheet" href="cdn"></link> -->
</head>
<body>
<!-- <img src="www.baud.xxx.png" alt="xxxx"/> -->
<!-- https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=34646,34528,34068,31254,34552,34004,34525,34585,34517,26350,34416,34556,34682&wd=ddd&req=2&bs=csdn&csor=3&pwd=dd&cb=jQuery1102023487320684976987_1632186297386&_=1632186297403 -->
<!-- https://www.baidu.com/sugrec?wd=a&b=show -->
<!-- https://www.baidu.com/sugrec?pre=1
&p=3
&ie=utf8
&json=1
&prod=pc
&from=pc_web
&sugsid=34646,34528,34068,31254,34552,34004,34525,34585,34517,26350,34416,34556,34682
&wd=ddd
&req=2
&bs=csdn
&csor=3
&pwd=dd
&cb=jQuery1102023487320684976987_1632186297386
&_=1632186297403 -->
<script>
function jsonp(url,params,cb){
return new Promise((resolve,reject)=>{
let script = document.createElement('script')
window['cd'] = function(data){
resolve(data)
document.body.removeChild(script)//掉完回调函数再删除掉script
}
params = {...params,cb}//wd=b&cb=show
let arrs = []
for(let key in params){
arrs.push(`${key}=${params[key]}`)
}
script.src = `${url}?${arrs.join('&')}`
document.body.appendChild(script)
})
}
jsonp({
url:'https://www.baidu.com/sugrec',
params:{pre:1},
cb:'show'
}).then(data=>{
console.log(data)
})
</script>
//1、jsonp缺点,只能发送get 请求,不支持 post ,put ,delete
//2、不安全 xss攻击 不采用
</body>
</html>
2、CORS 需要浏览器和后端同时支持。IE 8 和 9 需要通过 XDomainRequest 来实现。
浏览器会自动进行 CORS 通信,实现 CORS 通信的关键是后端。只要后端实现了 CORS,就实现了跨域。
服务端设置 Access-Control-Allow-Origin 就可以开启 CORS。 该属性表示哪些域名可以访问资源,如果设置通配符则表示所有网站都可以访问资源。
虽然设置 CORS 和前端没什么关系,但是通过这种方式解决跨域问题的话,会在发送请求时出现两种情况,分别为简单请求和复杂请求。
- 简单请求
只要同时满足以下两大条件,就属于简单请求
条件1:使用下列方法之一:
GET
HEAD
POST
条件2:Content-Type 的值仅限于下列三者之一:
text/plain
multipart/form-data
application/x-www-form-urlencoded
请求中的任意 XMLHttpRequestUpload 对象均没有注册任何事件监听器; XMLHttpRequestUpload 对象可以使用 XMLHttpRequest.upload 属性访问。
- 复杂请求
不符合以上条件的请求就肯定是复杂请求了。
复杂请求的CORS请求,会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求,该请求是 option 方法的,通过该请求来知道服务端是否允许跨域请求。
我们用PUT向后台请求时,属于复杂请求,后台需做如下配置:
// 允许哪个方法访问我
res.setHeader('Access-Control-Allow-Methods', 'PUT')
// 预检的存活时间
res.setHeader('Access-Control-Max-Age', 6)
// OPTIONS请求不做任何处理
if (req.method === 'OPTIONS') {
res.end()
}
// 定义后台返回的内容
app.put('/getData', function(req, res) {
console.log(req.headers)
res.end('我不爱你')
})
接下来我们看下一个完整复杂请求的例子,并且介绍下CORS请求相关的字段
// index.html
let xhr = new XMLHttpRequest()
document.cookie = 'name=xiamen' // cookie不能跨域
xhr.withCredentials = true // 前端设置是否带cookie
xhr.open('PUT', 'http://localhost:4000/getData', true)
xhr.setRequestHeader('name', 'xiamen')
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
console.log(xhr.response)
//得到响应头,后台需设置Access-Control-Expose-Headers
console.log(xhr.getResponseHeader('name'))
}
}
}
xhr.send()
//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)
上述代码由http://localhost:3000/index.html向http://localhost:4000/跨域请求,正如我们上面所说的,后端是实现 CORS 通信的关键。
3、postMessage (两个页面间的通信)
postMessage是HTML5 XMLHttpRequest Level 2中的API,且是为数不多可以跨域操作的window属性之一,它可用于解决以下方面的问题:
页面和其打开的新窗口的数据传递
多窗口之间消息传递
页面与嵌套的iframe消息传递
上面三个场景的跨域数据传递
postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。
接下来我们看个例子: http://localhost:3000/a.html页面向http://localhost:4000/b.html传递“你好吗”,然后后者传回"我很好"。
a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<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)
}
</script>
</body>
</html>
b.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
window.onmessage = function(e){
console.log(e.data)
e.source.postMessage('我很好',e.origin)
}
</script>
</body>
</html>
a.js
let express = require('express');
let app = express();
app.use(express.static(__dirname));
app.listen(3000);
b.js
let express = require('express');
let app = express();
app.use(express.static(__dirname));
app.listen(4000);
4.window.name
window.name属性的独特之处:name值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。
其中a.html和b.html是同域的,都是http://localhost:3000;而c.html是http://localhost:4000
a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
a和b 是同域的http://localhost:3000
c是独立的 http://localhost:4000
a获取c的数据
a先引用c c把值放到window.name ,把a引用的地址改到b
<iframe src="http://localhost:4000/c.html" id="iframe" frameborder="0" onload="load()"></iframe>
<script>
let first = true
function load(){
if(first){//第一次
let iframe = document.getElementById('iframe')
iframe.src = 'http://localhost:3000/b.html'
first = false
}else{//第二次
console.log(iframe.contentWindow.name)
}
}
</script>
</body>
</html>
b.html的页面是空的,就是个跑龙套的
c.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
window.name = '我很好'
</script>
</body>
</html>
a.js
let express = require('express');
let app = express();
app.use(express.static(__dirname));
app.listen(3000);
b.js
let express = require('express');
let app = express();
app.use(express.static(__dirname));
app.listen(4000);
总结:通过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。
5、hash
6、domian
7、webscoket
Websocket是HTML5的一个持久化的协议,它实现了浏览器与服务器的全双工通信,同时也是跨域的一种解决方案。WebSocket和HTTP都是应用层协议,都基于 TCP 协议。但是 WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。同时,WebSocket 在建立连接时需要借助 HTTP 协议,连接建立好了之后 client 与 server 之间的双向通信就与 HTTP 无关了。
原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。