首先了解一下同源策略:同源策略、SOP是一種約定拾徙,是瀏覽器最核心也會(huì)是最基本的安全功能洲炊,如果缺少了同源側(cè)羅,瀏覽器很容易受到XSS尼啡、CSRF等攻擊暂衡。所謂同源就是指“協(xié)議+端口+域名”三者相同,即便兩個(gè)不同的域名指向同一個(gè)IP地址崖瞭,也非同源狂巢。
怎么解決跨域問題?
? ? 1.通過jsonp跨域
? ? ? ? 原生實(shí)現(xiàn):
? ???????????var?script = document.createElement('script');
????????????script.type = 'text/javascript';
????????????// 傳參并指定回調(diào)執(zhí)行函數(shù)為onBack
????????????script.src = 'http://www.....:8080/login?user=admin&callback=onBack';
????????????document.head.appendChild(script);
????????????// 回調(diào)執(zhí)行函數(shù)
????????????function?onBack(res) {
????????????????alert(JSON.stringify(res));
????????????}
2.document.domain+iframe跨域
此方案僅限主域相同,子域不同的跨域應(yīng)用場景
1>]父窗口:(http://www.domain.com/a.html)
<iframe id="iframe"?src="http://child.domain.com/b.html"></iframe>
????????????<script>
????????????????document.domain = 'domain.com';
????????????????var?user = 'admin';
????????????</script>
[if !supportLists]2>[endif]子窗口(http://child.domain.com/b.html)
? <script>
????????????????document.domain = 'domain.com';
????????????????// 獲取父窗口中變量
????????????????alert('get js data from parent ---> '?+ window.parent.user);
????????????</script>
弊端:查看頁面渲染優(yōu)化
3.nginx代理跨域
4.nodejs中間件代理跨域
5.后端在頭部信息里面設(shè)置安全域名