awesome-interview/book1/browser-cross-origin.html

19 lines
22 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="generator" content="Docusaurus v2.0.0-beta.5">
<link rel="search" type="application/opensearchdescription+xml" title="HZFE - 剑指前端 Offer" href="/awesome-interview/opensearch.xml">
<link rel="preconnect" href="https://hm.baidu.com">
<script>var _hmt=_hmt||[];!function(){var e=document.createElement("script");e.src="https://hm.baidu.com/hm.js?c7cd0fd77ac518cc6ef46461cdc9524b";var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(e,c)}()</script><title data-react-helmet="true">浏览器跨域 | HZFE - 剑指前端 Offer</title><meta data-react-helmet="true" name="twitter:card" content="summary_large_image"><meta data-react-helmet="true" property="og:url" content="https://febook.hzfe.org/awesome-interview/book1/browser-cross-origin"><meta data-react-helmet="true" name="docsearch:language" content="en"><meta data-react-helmet="true" name="docsearch:version" content="current"><meta data-react-helmet="true" name="docsearch:docusaurus_tag" content="docs-default-current"><meta data-react-helmet="true" property="og:title" content="浏览器跨域 | HZFE - 剑指前端 Offer"><meta data-react-helmet="true" name="description" content="相关问题"><meta data-react-helmet="true" property="og:description" content="相关问题"><link data-react-helmet="true" rel="shortcut icon" href="/awesome-interview/img/favicon.ico"><link data-react-helmet="true" rel="canonical" href="https://febook.hzfe.org/awesome-interview/book1/browser-cross-origin"><link data-react-helmet="true" rel="alternate" href="https://febook.hzfe.org/awesome-interview/book1/browser-cross-origin" hreflang="en"><link data-react-helmet="true" rel="alternate" href="https://febook.hzfe.org/awesome-interview/book1/browser-cross-origin" hreflang="x-default"><link data-react-helmet="true" rel="preconnect" href="https://BH4D9OD16A-dsn.algolia.net" crossorigin="anonymous"><link rel="stylesheet" href="/awesome-interview/assets/css/styles.304d13b7.css">
<link rel="preload" href="/awesome-interview/assets/js/runtime~main.e4536af0.js" as="script">
<link rel="preload" href="/awesome-interview/assets/js/main.52f9823f.js" as="script">
</head>
<body>
<script>!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}()</script><div id="__docusaurus">
<div><a href="#" class="skipToContent_1oUP">Skip to main content</a></div><nav class="navbar navbar--fixed-top navbarHideable_2qcr"><div class="navbar__inner"><div class="navbar__items"><button aria-label="Navigation bar toggle" class="navbar__toggle clean-btn" type="button" tabindex="0"><svg width="30" height="30" viewBox="0 0 30 30" aria-hidden="true"><path stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="2" d="M4 7h22M4 15h22M4 23h22"></path></svg></button><a class="navbar__brand" href="/awesome-interview/"><img src="/awesome-interview/img/badge.svg" alt="HZFE" class="themedImage_1VuW themedImage--light_3UqQ navbar__logo"><img src="/awesome-interview/img/badge.svg" alt="HZFE" class="themedImage_1VuW themedImage--dark_hz6m navbar__logo"><b class="navbar__title">剑指前端 Offer</b></a></div><div class="navbar__items navbar__items--right"><a href="https://github.com/hzfe/awesome-interview" target="_blank" rel="noopener noreferrer" class="navbar__item navbar__link"><span>GitHub<svg width="13.5" height="13.5" aria-hidden="true" viewBox="0 0 24 24" class="iconExternalLink_3J9K"><path fill="currentColor" d="M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"></path></svg></span></a><div class="searchBox_1Doo"><button type="button" class="DocSearch DocSearch-Button" aria-label="Search"><span class="DocSearch-Button-Container"><svg width="20" height="20" class="DocSearch-Search-Icon" viewBox="0 0 20 20"><path d="M14.386 14.386l4.0877 4.0877-4.0877-4.0877c-2.9418 2.9419-7.7115 2.9419-10.6533 0-2.9419-2.9418-2.9419-7.7115 0-10.6533 2.9418-2.9419 7.7115-2.9419 10.6533 0 2.9419 2.9418 2.9419 7.7115 0 10.6533z" stroke="currentColor" fill="none" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="round"></path></svg><span class="DocSearch-Button-Placeholder">Search</span></span><span class="DocSearch-Button-Keys"></span></button></div></div></div><div role="presentation" class="navbar-sidebar__backdrop"></div></nav><div class="main-wrapper docs-wrapper docs-doc-page"><div class="docPage_31aa"><button class="clean-btn backToTopButton_35hR" type="button"><svg viewBox="0 0 24 24" width="28"><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z" fill="currentColor"></path></svg></button><aside class="docSidebarContainer_3Kbt"><div class="sidebar_15mo sidebarWithHideableNavbar_267A"><a tabindex="-1" class="sidebarLogo_3h0W" href="/awesome-interview/"><img src="/awesome-interview/img/badge.svg" alt="HZFE" class="themedImage_1VuW themedImage--light_3UqQ"><img src="/awesome-interview/img/badge.svg" alt="HZFE" class="themedImage_1VuW themedImage--dark_hz6m"><b>剑指前端 Offer</b></a><nav class="menu thin-scrollbar menu_Bmed menuWithAnnouncementBar_2WvA"><ul class="menu__list"><li class="menu__list-item"><a class="menu__link" href="/awesome-interview/about">关于我们</a></li><li class="menu__list-item"><a class="menu__link" href="/awesome-interview/">前言</a></li><li class="menu__list-item"><a class="menu__link menu__link--sublist menu__link--active" href="#">模拟题一</a><ul style="display:block;overflow:visible;height:auto" class="menu__list"><li class="menu__list-item"><a class="menu__link menu__link--active" aria-current="page" tabindex="0" href="/awesome-interview/book1/browser-cross-origin">浏览器:浏览器跨域</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/browser-repain-reflow">浏览器:浏览器的重排重绘</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/engineer-webpack-workflow">工程化Webpack 工作流程</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/frame-vue-data-binding">框架Vue 的数据绑定机制</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/frame-vue-computed-watch">框架Vue 的 computed 和 watch 的区别</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/js-closures">基础:闭包的作用和原理</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/js-module-specs">基础:前端模块化规范</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/css-bfc">样式BFC 的形成和作用</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/network-security">网络:前端安全</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/coding-promise">编码:实现一个 Promises/A+</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/algorithm-balanced-binary-trees">算法:平衡二叉树</a></li><li class="menu__list-item"><a class="menu__link" tabindex="0" href="/awesome-interview/book1/topic-enter-url-display-xx">综合:浏览器从输入网址到页面展现的过程</a></li></ul></li><li class="menu__list-item menu__list-item--collapsed"><a class="menu__link menu__link--sublist" href="#">模拟题二</a></li><li class="menu__list-item menu__list-item--collapsed"><a class="menu__link menu__link--sublist" href="#">模拟题三</a></li></ul></nav><button type="button" title="Collapse sidebar" aria-label="Collapse sidebar" class="button button--secondary button--outline collapseSidebarButton_1CGd"><svg width="20" height="20" aria-hidden="true" class="collapseSidebarButtonIcon_3E-R"><g fill="#7a7a7a"><path d="M9.992 10.023c0 .2-.062.399-.172.547l-4.996 7.492a.982.982 0 01-.828.454H1c-.55 0-1-.453-1-1 0-.2.059-.403.168-.551l4.629-6.942L.168 3.078A.939.939 0 010 2.528c0-.548.45-.997 1-.997h2.996c.352 0 .649.18.828.45L9.82 9.472c.11.148.172.347.172.55zm0 0"></path><path d="M19.98 10.023c0 .2-.058.399-.168.547l-4.996 7.492a.987.987 0 01-.828.454h-3c-.547 0-.996-.453-.996-1 0-.2.059-.403.168-.551l4.625-6.942-4.625-6.945a.939.939 0 01-.168-.55 1 1 0 01.996-.997h3c.348 0 .649.18.828.45l4.996 7.492c.11.148.168.347.168.55zm0 0"></path></g></svg></button></div></aside><main class="docMainContainer_3ufF"><div class="container padding-top--md padding-bottom--lg"><div class="row"><div class="col docItemCol_3FnS"><div class="docItemContainer_33ec"><article><div class="tocCollapsible_1PrD tocMobile_3Hoh"><button type="button" class="clean-btn tocCollapsibleButton_2O1e">On this page</button></div><div class="markdown"><header><h1>浏览器跨域</h1></header><h2><a aria-hidden="true" tabindex="-1" class="anchor anchor__h2 anchorWithHideOnScrollNavbar_3R7-" id="相关问题"></a>相关问题<a class="hash-link" href="#相关问题" title="Direct link to heading">#</a></h2><ul><li>什么是跨域</li><li>为什么会跨域</li><li>为什么有跨域限制</li><li>怎么解决跨域</li></ul><h2><a aria-hidden="true" tabindex="-1" class="anchor anchor__h2 anchorWithHideOnScrollNavbar_3R7-" id="回答关键点"></a>回答关键点<a class="hash-link" href="#回答关键点" title="Direct link to heading">#</a></h2><p><code>CORS</code><sup>[1]</sup> <code>同源策略</code><sup>[2]</sup></p><p>跨域问题的来源是浏览器为了<strong>请求安全</strong>而引入的基于<strong>同源策略</strong>的安全特性。当页面和请求的<strong>协议</strong><strong>主机名</strong><strong>端口</strong>不同时,浏览器判定两者不同源,即为跨域请求。需要注意的是跨域是<strong>浏览器的限制</strong>,服务端并不受此影响。当产生跨域时,我们可以通过 JSONP、CORS、postMessage 等方式解决。</p><h2><a aria-hidden="true" tabindex="-1" class="anchor anchor__h2 anchorWithHideOnScrollNavbar_3R7-" id="知识点深入"></a>知识点深入<a class="hash-link" href="#知识点深入" title="Direct link to heading">#</a></h2><h3><a aria-hidden="true" tabindex="-1" class="anchor anchor__h3 anchorWithHideOnScrollNavbar_3R7-" id="1-跨域问题的来源"></a>1. 跨域问题的来源<a class="hash-link" href="#1-跨域问题的来源" title="Direct link to heading">#</a></h3><p>跨域问题的来源是浏览器为了<strong>请求安全</strong>而引入的基于<strong>同源策略Same-origin policy</strong>的安全特性。同源策略是浏览器一个非常重要的安全策略,基于这个策略可以限制非同源的内容与当前页面进行交互,从而减少页面被攻击的可能性。</p><p>当页面和请求的<strong>协议</strong><strong>主机名</strong><strong>端口</strong>不同时,浏览器判定两者不同源,从而产生跨域。需要注意的是跨域是<strong>浏览器的限制</strong>,实际请求已经正常发出和响应了。</p><h3><a aria-hidden="true" tabindex="-1" class="anchor anchor__h3 anchorWithHideOnScrollNavbar_3R7-" id="2-如何判定跨域"></a>2. 如何判定跨域<a class="hash-link" href="#2-如何判定跨域" title="Direct link to heading">#</a></h3><p><img src="https://user-images.githubusercontent.com/3984824/126035945-024df466-a92f-4564-82c5-cb5d54d66466.png" alt="cors"></p><p>如上图所示,一个 origin 由<strong>协议Protocol</strong><strong>主机名Host</strong><strong>端口Port</strong>组成,这三块也是同源策略的判定条件,只有当<strong>协议</strong><strong>主机名</strong><strong>端口</strong>都相同时,浏览器才判定两者是同源关系,否则即为跨域。</p><h3><a aria-hidden="true" tabindex="-1" class="anchor anchor__h3 anchorWithHideOnScrollNavbar_3R7-" id="3-跨域的解决方案"></a>3. 跨域的解决方案<a class="hash-link" href="#3-跨域的解决方案" title="Direct link to heading">#</a></h3><p>前端常见的跨域解决方案有 CORS、反代、JSONP 等。</p><h4><a aria-hidden="true" tabindex="-1" class="anchor anchor__h4 anchorWithHideOnScrollNavbar_3R7-" id="31-cors-cross-origin-resource-sharing"></a>3.1 CORS (Cross-Origin Resource Sharing)<a class="hash-link" href="#31-cors-cross-origin-resource-sharing" title="Direct link to heading">#</a></h4><p>CORS 是目前最为广泛的解决跨域问题的方案。方案依赖服务端/后端在响应头中添加 <code>Access-Control-Allow-*</code> 头,告知浏览器端通过此请求。</p><p><strong>涉及到的端</strong></p><p>CORS 只需要服务端/后端支持即可,不涉及前端改动。</p><p><strong>具体实现方式</strong></p><p>CORS 将请求分为<strong>简单请求Simple Requests</strong><strong>需预检请求Preflighted requests</strong>,不同场景有不同的行为:</p><p><strong>简单请求</strong></p><p>不会触发预检请求的称为简单请求。当请求满足以下条件时就是一个简单请求:</p><ul><li>请求方法:<code>GET</code><code>HEAD</code><code>POST</code></li><li>请求头:<code>Accept</code><code>Accept-Language</code><code>Content-Language</code><code>Content-Type</code><ul><li>Content-Type 仅支持:<code>application/x-www-form-urlencoded</code><code>multipart/form-data</code><code>text/plain</code></li></ul></li></ul><p><strong>需预检请求</strong></p><p>当一个请求不满足以上简单请求的条件时,浏览器会自动向服务端发送一个 <strong>OPTIONS</strong> 请求,通过服务端返回的 <code>Access-Control-Allow-*</code> 判定请求是否被允许。</p><p>CORS 引入了以下几个以 <code>Access-Control-Allow-*</code> 开头:</p><ul><li><code>Access-Control-Allow-Origin</code> 表示允许的来源</li><li><code>Access-Control-Allow-Methods</code> 表示允许的请求方法</li><li><code>Access-Control-Allow-Headers</code> 表示允许的请求头</li><li><code>Access-Control-Allow-Credentials</code> 表示允许携带认证信息</li></ul><p>当请求符合响应头的这些条件时,浏览器才会发送并响应正式的请求。</p><h4><a aria-hidden="true" tabindex="-1" class="anchor anchor__h4 anchorWithHideOnScrollNavbar_3R7-" id="32-反向代理"></a>3.2 反向代理<a class="hash-link" href="#32-反向代理" title="Direct link to heading">#</a></h4><p>反向代理解决跨域问题的方案依赖同源的服务端对请求做一个转发处理,将请求从跨域请求转换成同源请求。</p><p><strong>涉及到的端</strong></p><p>反向代理只需要服务端/后端支持,几乎不涉及前端改动,只用切换接口即可。</p><p><strong>具体实现方式</strong></p><p>反向代理的实现方式为在页面同域下配置一套反向代理服务,页面请求同域的服务端,服务端请求上游的实际的服务端,之后将结果返回给前端。</p><h4><a aria-hidden="true" tabindex="-1" class="anchor anchor__h4 anchorWithHideOnScrollNavbar_3R7-" id="33-jsonp"></a>3.3 JSONP<a class="hash-link" href="#33-jsonp" title="Direct link to heading">#</a></h4><p>JSONP 是一个相对古老的跨域解决方案。主要是利用了浏览器加载 JavaScript 资源文件时不受同源策略的限制而实现跨域获取数据。</p><p><strong>涉及到的端</strong></p><p>JSONP 需要服务端和前端配合实现。</p><p><strong>具体实现方式</strong></p><p>JSONP 的原理是利用了浏览器加载 JavaScript 资源文件时不受同源策略的限制而实现的。具体流程如下:</p><ol><li>全局注册一个函数,例如:<code>window.getHZFEMember = (num) =&gt; console.log(&#x27;HZFE Member: &#x27; + hzfeMember);</code></li><li>构造一个请求 URL例如<code>https://hzfe.org/api/hzfeMember?callback=getHZFEMember</code></li><li>生成一个 <code>&lt;script&gt;</code> 并把 <code>src</code> 设为上一步的请求 URL 并插入到文档中,如 <code>&lt;script src=&quot;https://hzfe.org/api/hzfeMember?callback=getHZFEMember&quot; /&gt;</code></li><li>服务端构造一个 JavaScript 函数调用表达式并返回,例如:<code>getHZFEMember(17)</code></li><li>浏览器加载并执行以上代码,输出 <code>HZFE Member: 17</code></li></ol><h4><a aria-hidden="true" tabindex="-1" class="anchor anchor__h4 anchorWithHideOnScrollNavbar_3R7-" id="非常用方式"></a>非常用方式<a class="hash-link" href="#非常用方式" title="Direct link to heading">#</a></h4><ul><li><strong>postMessage</strong><ul><li>即在两个 origin 下分别部署一套页面 A 与 BA 页面通过 <code>iframe</code> 加载 B 页面并监听消息B 页面发送消息。</li></ul></li><li><strong>window.name</strong><ul><li>主要是利用 <code>window.name</code> 页面跳转不改变的特性实现跨域,即 <code>iframe</code> 加载一个跨域页面,设置 <code>window.name</code>,跳转到同域页面,可以通过 <code>$(&#x27;iframe&#x27;).contentWindow.name</code> 拿到跨域页面的数据。</li></ul></li><li><strong>document.domain</strong><ul><li>可将相同一级域名下的子域名页面的 <code>document.domain</code> 设置为一级域名实现跨域。</li><li>可将同域不同端口的 <code>document.domain</code> 设置为同域名实现跨域(端口被置为 null</li></ul></li></ul><h2><a aria-hidden="true" tabindex="-1" class="anchor anchor__h2 anchorWithHideOnScrollNavbar_3R7-" id="扩展阅读"></a>扩展阅读<a class="hash-link" href="#扩展阅读" title="Direct link to heading">#</a></h2><h3><a aria-hidden="true" tabindex="-1" class="anchor anchor__h3 anchorWithHideOnScrollNavbar_3R7-" id="1-localstorage--sessionstorage-跨域"></a>1. LocalStorage / SessionStorage 跨域<a class="hash-link" href="#1-localstorage--sessionstorage-跨域" title="Direct link to heading">#</a></h3><p>LocalStorage 和 SessionStorage 同样受到同源策略的限制。而跨域读写的方式也可以使用前文提到的 postMessage。</p><h3><a aria-hidden="true" tabindex="-1" class="anchor anchor__h3 anchorWithHideOnScrollNavbar_3R7-" id="2-跨域与监控"></a>2. 跨域与监控<a class="hash-link" href="#2-跨域与监控" title="Direct link to heading">#</a></h3><p>前端项目在统计前端报错监控时会遇到上报的内容只有 <code>Script Error</code> 的问题。这个问题也是由同源策略引起。在 <code>&lt;script&gt;</code> 标签上添加 <code>crossorigin=&quot;anonymous&quot;</code> 并且返回的 JS 文件响应头加上 <code>Access-Control-Allow-Origin: *</code> 即可捕捉到完整的错误堆栈。</p><h3><a aria-hidden="true" tabindex="-1" class="anchor anchor__h3 anchorWithHideOnScrollNavbar_3R7-" id="3-跨域与图片"></a>3. 跨域与图片<a class="hash-link" href="#3-跨域与图片" title="Direct link to heading">#</a></h3><p>前端项目在图片处理时可能会遇到图片绘制到 Canvas 上之后却不能读取像素或导出 base64 的问题。这个问题也是由同源策略引起。解决方式和上文相同,给图片添加 <code>crossorigin=&quot;anonymous&quot;</code> 并在返回的图片文件响应头加上 <code>Access-Control-Allow-Origin: *</code> 即可解决。</p><h2><a aria-hidden="true" tabindex="-1" class="anchor anchor__h2 anchorWithHideOnScrollNavbar_3R7-" id="参考资料"></a>参考资料<a class="hash-link" href="#参考资料" title="Direct link to heading">#</a></h2><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" target="_blank" rel="noopener noreferrer">Cross-Origin Resource Sharing (CORS)</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy" target="_blank" rel="noopener noreferrer">Same-origin policy</a></li></ol></div></article><nav class="pagination-nav docusaurus-mt-lg" aria-label="Docs pages navigation"><div class="pagination-nav__item"><a class="pagination-nav__link" href="/awesome-interview/"><div class="pagination-nav__sublabel">Previous</div><div class="pagination-nav__label">« 前言</div></a></div><div class="pagination-nav__item pagination-nav__item--next"><a class="pagination-nav__link" href="/awesome-interview/book1/browser-repain-reflow"><div class="pagination-nav__sublabel">Next</div><div class="pagination-nav__label">浏览器:浏览器的重排重绘 »</div></a></div></nav></div></div><div class="col col--3"><div class="tableOfContents_35-E thin-scrollbar"><ul class="table-of-contents table-of-contents__left-border"><li><a href="#相关问题" class="table-of-contents__link">相关问题</a></li><li><a href="#回答关键点" class="table-of-contents__link">回答关键点</a></li><li><a href="#知识点深入" class="table-of-contents__link">知识点深入</a><ul><li><a href="#1-跨域问题的来源" class="table-of-contents__link">1. 跨域问题的来源</a></li><li><a href="#2-如何判定跨域" class="table-of-contents__link">2. 如何判定跨域</a></li><li><a href="#3-跨域的解决方案" class="table-of-contents__link">3. 跨域的解决方案</a></li></ul></li><li><a href="#扩展阅读" class="table-of-contents__link">扩展阅读</a><ul><li><a href="#1-localstorage--sessionstorage-跨域" class="table-of-contents__link">1. LocalStorage / SessionStorage 跨域</a></li><li><a href="#2-跨域与监控" class="table-of-contents__link">2. 跨域与监控</a></li><li><a href="#3-跨域与图片" class="table-of-contents__link">3. 跨域与图片</a></li></ul></li><li><a href="#参考资料" class="table-of-contents__link">参考资料</a></li></ul></div></div></div><div class="row"><div class="col"><div class="react-utterences"><div>Loading script...</div></div></div><div class="col col--3"></div></div></div></main></div></div></div>
<script src="/awesome-interview/assets/js/runtime~main.e4536af0.js"></script>
<script src="/awesome-interview/assets/js/main.52f9823f.js"></script>
</body>
</html>