Web前端 跨域
跨域
同源策略
协议 域名 端口 同域
为什么浏览器不支持跨域
cookie LocalStorage
DOM元素也有同源策略 iframe
ajax 也不支持跨域
实现跨域
- jsonp
- cors
- postMessage
- document.domain
- window.name
- location.hash
- http-proxy
- mgox
- websocket
jsonp
利用script标签的跨域性
只能发送get请求 不支持post put delete
不安全 xss攻击, 不采用,返回可能含有script标签
CROS
浏览器屏蔽了跨域响应
如果想要允许这种跨域请求,可以在服务器返回response头信息中添加以下字段来限定那些地址的跨域请求可以被允许:
- Access-Control-Allow-Origin : htt[😕/baidu.com
设置只允许百度来跨域访问这个服务
预请求
默认允许(这里的允许指不需要与请求验证)的方法只有GET、HEAD、POST,对于其余的方法请求,浏览器要先对服务器进行预请求再进行处理。
默认允许的Content-Type为:text/plain,multipart/form-data,application/x-www-form-urlenncoded
其余限制:
- 请求头限制(主要)
- XMLHttpRequestUpload对象没有注册任何事件监听器
- 请求中没有使用ReadableStream对象
端口服务改动:
- 'Access-Control-Allow-Origin' : 'http://baidu.com', //只允许百度来访问这个服务
- 'Access-Control-Allow-Headers' : 'X-Test-Cors', //允许含有这个头信息的request请求服务
- 'Access-Control-Allow-Methods' : 'POST,PUT,DELETE',
- 'Access-Control-Max-Age' : '1000' //1000秒之内,上面的请求,不需要预请求,可以直接发送请求
postMessage
function load(){
let frame = document.getElementById('frame')
frame.contentWindow.postMessage('我爱你', 'http://localhost:4000')
}
window.onmessage = function(e){
console.log(e.data);
}
iframe:
window.onmessage = function(e){
console.log(e.data);
e.source.postMessage('我不爱你', e.origin)
}
我爱你
我不爱你
window.name
a和b是同域的 http://localhost:3000
c是独立的 http://localhost:4000
a获取c的数据
a先引用c c把值放到window.name, 把a引用的地址改到b
a:
<iframe src = "http://localhost:4000/c.html" frameborder="0" onload="load()" id="iframe"></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>
c:
<script>
window.name = "我爱你"
</script>
location.hash
路径后面的hash值可以用来通信
目的a想访问c,
a给c传一个hash值, c收到hash值后,c把hash值传递给b,b将结果放到a的hash值中
a:
<iframe src="http://localhost:4000/c.html#iloveyou"></iframe>
<script>
window.onhashchange = function(){
console.log(location.hash);
}
</script>
c:
<script>
console.log(location.hash)
let iframe = document.createElement('iframe')
iframe.src = 'http://localhost:3000/b.html#idontloveyou';
document.body.appendChild(iframe)
</script>
b:
<script>
window.parent.parent.location.hash = location.hash
</script>
document.domain
高级api 不兼容 socket.io(一般使用它)
<script>
let socket = new WebSocket('ws://localhost:3000');
socket.onopen = function(){
socket.send('我爱你');
}
socket.onmessage = function(e){
console.log(e.data);
}
</script>
服务器
let WebSocket = require('ws');
let wss = new WebSocket.Server({port:3000})
wss.on('connection', function(ws){
wss.on('message', function(data){
console.log(data);
})
})

浙公网安备 33010602011771号