跨域的集中方法:
一、JSONP
缺点只能获取get请求,需要后端配合返回cb(data)。
二、CORS
后端各种设置header
res.SetHeaders(Access-Control-Allow-Origin, "")
res.SetHeaders(Access-Control-Allow-Credentials, "")
res.SetHeaders(Access-Control-Expose-Headers, "")
三、postMessage
域A页面A.html中使用iframe嵌套域B的B.html,则A.html中这么写:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
我是A
<iframe src="http://localhost:4000/B.html" frameborder="0" id="iframe" onload="handleLoaded()"></iframe>
<script>
function handleLoaded() {
let iframe = document.getElementById('iframe');
iframe.contentWindow.postMessage('hello?','http://localhost:4000')
}
window.onmessage = function (e) {
console.log('回消息了', e.data)
}
</script>
</body>
</html>
B中这么写:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
</style>
<title>测试</title>
</head>
<body>
我是C
<script>
window.onmessage=function(e){
console.log(e,'e')
e.source.postMessage('我是土豆',e.origin)
}
</script>
</body>
</html>
需要注意的一点是测试的时候,A代码中iframe的src地址要写成隔壁域名下的B.html,造成我测试的时候总是报如下错误:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:4000') does not match the recipient window's origin ('http://localhost:3000').
四、document.domin
只适合同一主域名下的的网页通信。方法就是给要通信的网页script代码下面都放上document.domin="XXX",即可。
五、window.name
AB同域、C独立域,A嵌套C,C设置window.name,A中C加载完毕后,将iframe的src换成B,但是window.name不会变,好像是bug一样。
六、location.hash
AB同域、C独立域,A嵌套C,C动态加载B,然后B通过parent.parent.location.hash=“”,然后A监听hashchange事件去拿hash变化。
七、nginx配置。
配置,类似CORS。
八、websoket。
不受同源策略限制。
九、webpack代理Proxy。