aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/http/cors/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/zh-cn/web/http/cors/index.html')
-rw-r--r--files/zh-cn/web/http/cors/index.html510
1 files changed, 510 insertions, 0 deletions
diff --git a/files/zh-cn/web/http/cors/index.html b/files/zh-cn/web/http/cors/index.html
new file mode 100644
index 0000000000..c7acc1344d
--- /dev/null
+++ b/files/zh-cn/web/http/cors/index.html
@@ -0,0 +1,510 @@
+---
+title: 跨源资源共享(CORS)
+slug: Web/HTTP/Access_control_CORS
+tags:
+ - AJAX
+ - CORS
+ - Cross-Origin Resource Sharing
+ - Fetch
+ - Fetch API
+ - HTTP
+ - HTTP Access Controls
+ - Same-origin policy
+ - Security
+ - XMLHttpRequest
+ - 'l10n:priority'
+translation_of: Web/HTTP/CORS
+---
+<div>{{HTTPSidebar}}</div>
+
+<p><strong>跨源资源共享</strong> ({{Glossary("CORS")}}) (或通俗地译为跨域资源共享)是一种基于{{Glossary("HTTP")}} 头的机制,该机制通过允许服务器标示除了它自己以外的其它{{glossary("origin")}}(域,协议和端口),这样浏览器可以访问加载这些资源。跨源资源共享还通过一种机制来检查服务器是否会允许要发送的真实请求,该机制通过浏览器发起一个到服务器托管的跨源资源的"预检"请求。在预检中,浏览器发送的头中标示有HTTP方法和真实请求中会用到的头。</p>
+
+<p>跨源HTTP请求的一个例子:运行在 http://domain-a.com 的JavaScript代码使用{{domxref("XMLHttpRequest")}}来发起一个到 https://domain-b.com/data.json 的请求。</p>
+
+<p>出于安全性,浏览器限制脚本内发起的跨源HTTP请求。 例如,XMLHttpRequest和Fetch API遵循同源策略。 这意味着使用这些API的Web应用程序只能从加载应用程序的同一个域请求HTTP资源,除非响应报文包含了正确CORS响应头。</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/14295/CORS_principle.png" style="height: 467px; width: 672px;"></p>
+
+<p>跨源域资源共享( {{Glossary("CORS")}} )机制允许 Web 应用服务器进行跨源访问控制,从而使跨源数据传输得以安全进行。现代浏览器支持在 API 容器中(例如 {{domxref("XMLHttpRequest")}} 或 <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a> )使用 CORS,以降低跨源 HTTP 请求所带来的风险。</p>
+
+<h2 id="谁应该读这篇文章?">谁应该读这篇文章?</h2>
+
+<p>说实话,每个人。</p>
+
+<p>更具体地来讲,这篇文章适用于网站管理员、后端和前端开发者。现代浏览器处理跨源资源共享的客户端部分,包括HTTP头和相关策略的执行。但是这一新标准意味着服务器需要处理新的请求头和响应头。对于服务端的支持,开发者可以阅读补充材料 <a class="internal" href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Server-Side_Access_Control" title="En/Server-Side Access Control">cross-origin sharing from a server perspective (with PHP code snippets)</a> 。</p>
+
+<h2 id="什么情况下需要_CORS_?">什么情况下需要 CORS ?</h2>
+
+<p>这份 <a class="external external-icon" href="http://www.w3.org/TR/cors/" title="http://www.w3.org/TR/cors/">cross-origin sharing standard</a> 允许在下列场景中使用跨站点 HTTP 请求:</p>
+
+<ul>
+ <li>前文提到的由 {{domxref("XMLHttpRequest")}} 或 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch</a> 发起的跨源 HTTP 请求。</li>
+ <li>Web 字体 (CSS 中通过<code> @font-face </code>使用跨源字体资源),<a class="external external-icon" href="https://www.w3.org/TR/css-fonts-3/#font-fetching-requirements" title="https://www.w3.org/TR/css-fonts-3/#font-fetching-requirements">因此,网站就可以发布 TrueType 字体资源,并只允许已授权网站进行跨站调用</a>。</li>
+ <li><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL">WebGL 贴图</a></li>
+ <li>使用 <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage">drawImage</a></code> 将 Images/video 画面绘制到 canvas</li>
+</ul>
+
+<p>本文概述了跨源资源共享机制及其所涉及的 HTTP 头。</p>
+
+<h2 id="功能概述">功能概述</h2>
+
+<p>跨源资源共享标准新增了一组 HTTP 首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源。另外,规范要求,对那些可能对服务器数据产生副作用的 HTTP 请求方法(特别是 {{HTTPMethod("GET")}} 以外的 HTTP 请求,或者搭配某些 MIME 类型的 {{HTTPMethod("POST")}} 请求),浏览器必须首先使用 {{HTTPMethod("OPTIONS")}} 方法发起一个预检请求(preflight request),从而获知服务端是否允许该跨源请求。服务器确认允许之后,才发起实际的 HTTP 请求。在预检请求的返回中,服务器端也可以通知客户端,是否需要携带身份凭证(包括 <a href="/zh-CN/docs/Web/HTTP/Cookies">Cookies </a>和 HTTP 认证相关数据)。</p>
+
+<p>CORS请求失败会产生错误,但是为了安全,在JavaScript代码层面是无法获知到底具体是哪里出了问题。你只能查看浏览器的控制台以得知具体是哪里出现了错误。</p>
+
+<p>接下来的内容将讨论相关场景,并剖析该机制所涉及的 HTTP 首部字段。</p>
+
+<h2 id="若干访问控制场景">若干访问控制场景</h2>
+
+<p>这里,我们使用三个场景来解释跨源资源共享机制的工作原理。这些例子都使用 {{domxref("XMLHttpRequest")}} 对象。</p>
+
+<p>本文中的 JavaScript 代码片段都可以从 <a href="http://arunranga.com/examples/access-control/">http://arunranga.com/examples/access-control/</a> 获得。另外,使用支持跨源  {{domxref("XMLHttpRequest")}} 的浏览器访问该地址,可以看到代码的实际运行结果。</p>
+
+<p>关于服务端对跨源资源共享的支持的讨论,请参见这篇文章: <a href="/zh-CN/docs/Web/HTTP/Server-Side_Access_Control">Server-Side_Access_Control (CORS)</a>。</p>
+
+<h3 id="简单请求">简单请求</h3>
+
+<p>某些请求不会触发 <a href="/zh-CN/docs/Web/HTTP/Access_control_CORS#Preflighted_requests">CORS 预检请求</a>。本文称这样的请求为“简单请求”,请注意,该术语并不属于 {{SpecName('Fetch')}} (其中定义了 CORS)规范。若请求满足所有下述条件,则该请求可视为“简单请求”:</p>
+
+<ul>
+ <li>使用下列方法之一:
+ <ul>
+ <li>{{HTTPMethod("GET")}}</li>
+ <li>{{HTTPMethod("HEAD")}}</li>
+ <li>{{HTTPMethod("POST")}}</li>
+ </ul>
+ </li>
+ <li><span class="short_text" id="result_box" lang="zh-CN"><span>除了被用户代理自动设置的首部字段(例如 </span></span>{{HTTPHeader("Connection")}} ,{{HTTPHeader("User-Agent")}}<span class="short_text" lang="zh-CN"><span>)和在 Fetch 规范中定义为 </span></span><a href="https://fetch.spec.whatwg.org/#forbidden-header-name">禁用首部名称</a><span class="short_text" lang="zh-CN"><span> 的其他首部,允许人为设置的字段为 Fetch 规范定义的 </span></span><a href="https://fetch.spec.whatwg.org/#cors-safelisted-request-header">对 CORS 安全的首部字段集合</a>。该集合为:
+ <ul>
+ <li>{{HTTPHeader("Accept")}}</li>
+ <li>{{HTTPHeader("Accept-Language")}}</li>
+ <li>{{HTTPHeader("Content-Language")}}</li>
+ <li>{{HTTPHeader("Content-Type")}} (需要注意额外的限制)</li>
+ <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#dpr">DPR</a></code></li>
+ <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#downlink">Downlink</a></code></li>
+ <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#save-data">Save-Data</a></code></li>
+ <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#viewport-width">Viewport-Width</a></code></li>
+ <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#width">Width</a></code></li>
+ </ul>
+ </li>
+ <li>{{HTTPHeader("Content-Type")}} 的值仅限于下列三者之一:
+ <ul>
+ <li><code>text/plain</code></li>
+ <li><code>multipart/form-data</code></li>
+ <li><code>application/x-www-form-urlencoded</code></li>
+ </ul>
+ </li>
+ <li>请求中的任意{{domxref("XMLHttpRequestUpload")}} 对象均没有注册任何事件监听器;{{domxref("XMLHttpRequestUpload")}} 对象可以使用 {{domxref("XMLHttpRequest.upload")}} 属性访问。</li>
+ <li>请求中没有使用 {{domxref("ReadableStream")}} 对象。</li>
+</ul>
+
+<div class="note"><strong>注意:</strong> 这些跨站点请求与浏览器发出的其他跨站点请求并无二致。如果服务器未返回正确的响应首部,则请求方不会收到任何数据。因此,那些不允许跨站点请求的网站无需为这一新的 HTTP 访问控制特性担心。</div>
+
+<div class="note"><strong>注意:</strong> WebKit Nightly 和 Safari Technology Preview 为{{HTTPHeader("Accept")}}, {{HTTPHeader("Accept-Language")}}, 和 {{HTTPHeader("Content-Language")}} 首部字段的值添加了额外的限制。如果这些首部字段的值是“非标准”的,WebKit/Safari 就不会将这些请求视为“简单请求”。WebKit/Safari 并没有在文档中列出哪些值是“非标准”的,不过我们可以在这里找到相关讨论:<a href="https://bugs.webkit.org/show_bug.cgi?id=165178" rel="nofollow noreferrer">Require preflight for non-standard CORS-safelisted request headers Accept, Accept-Language, and Content-Language</a>, <a href="https://bugs.webkit.org/show_bug.cgi?id=165566" rel="nofollow noreferrer">Allow commas in Accept, Accept-Language, and Content-Language request headers for simple CORS</a>, and <a href="https://bugs.webkit.org/show_bug.cgi?id=166363" rel="nofollow noreferrer">Switch to a blacklist model for restricted Accept headers in simple CORS requests</a>。其它浏览器并不支持这些额外的限制,因为它们不属于规范的一部分。</div>
+
+<p>比如说,假如站点 http://foo.example 的网页应用想要访问 http://bar.other 的资源。http://foo.example 的网页中可能包含类似于下面的 JavaScript 代码:</p>
+
+<pre class="brush: js notranslate" id="line1">var invocation = new XMLHttpRequest();
+var url = 'http://bar.other/resources/public-data/';
+
+function callOtherDomain() {
+ if(invocation) {
+ invocation.open('GET', url, true);
+ invocation.onreadystatechange = handler;
+ invocation.send();
+ }
+}
+</pre>
+
+<p><span class="short_text" id="result_box" lang="zh-CN"><span>客户端和服务器之间使用 CORS 首部字段来处理权限:</span></span></p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/17214/simple-req-updated.png" style="height: 490px; width: 1023px;"></p>
+
+<p>分别检视请求报文和响应报文:</p>
+
+<pre class="brush: shell notranslate">GET /resources/public-data/ HTTP/1.1
+Host: bar.other
+User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
+Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
+Accept-Language: en-us,en;q=0.5
+Accept-Encoding: gzip,deflate
+Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
+Connection: keep-alive
+Referer: http://foo.example/examples/access-control/simpleXSInvocation.html
+Origin: http://foo.example
+
+
+HTTP/1.1 200 OK
+Date: Mon, 01 Dec 2008 00:23:53 GMT
+Server: Apache/2.0.61
+Access-Control-Allow-Origin: *
+Keep-Alive: timeout=2, max=100
+Connection: Keep-Alive
+Transfer-Encoding: chunked
+Content-Type: application/xml
+
+[XML Data]
+</pre>
+
+<p>第 1~10 行是请求首部。第10行 的请求首部字段 {{HTTPHeader("Origin")}} 表明该请求来源于 <code>http://foo.example</code>。</p>
+
+<p>第 13~22 行是来自于 http://bar.other 的服务端响应。响应中携带了响应首部字段 {{HTTPHeader("Access-Control-Allow-Origin")}}(第 16 行)。使用 {{HTTPHeader("Origin")}} 和 {{HTTPHeader("Access-Control-Allow-Origin")}} 就能完成最简单的访问控制。本例中,服务端返回的 <code>Access-Control-Allow-Origin: *</code> 表明,该资源可以被<strong>任意</strong>外域访问。如果服务端仅允许来自 http://foo.example 的访问,该首部字段的内容如下:</p>
+
+<p><code>Access-Control-Allow-Origin: http://foo.example</code></p>
+
+<p>现在,除了 http://foo.example,其它外域均不能访问该资源(该策略由请求首部中的 ORIGIN 字段定义,见第10行)。<code>Access-Control-Allow-Origin</code> 应当为 * 或者包含由 Origin 首部字段所指明的域名。</p>
+
+<h3 id="预检请求">预检请求</h3>
+
+<p>与前述简单请求不同,“需预检的请求”要求必须首先使用 {{HTTPMethod("OPTIONS")}}   方法发起一个预检请求到服务器,以获知服务器是否允许该实际请求。"预检请求“的使用,可以避免跨域请求对服务器的用户数据产生未预期的影响。</p>
+
+<p>如下是一个需要执行预检请求的 HTTP 请求:</p>
+
+<pre class="brush: js notranslate">var invocation = new XMLHttpRequest();
+var url = 'http://bar.other/resources/post-here/';
+var body = '&lt;?xml version="1.0"?&gt;&lt;person&gt;&lt;name&gt;Arun&lt;/name&gt;&lt;/person&gt;';
+
+function callOtherDomain(){
+ if(invocation)
+ {
+ invocation.open('POST', url, true);
+ invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
+ invocation.setRequestHeader('Content-Type', 'application/xml');
+ invocation.onreadystatechange = handler;
+ invocation.send(body);
+ }
+}
+
+......
+</pre>
+
+<p>上面的代码使用 POST 请求发送一个 XML 文档,该请求包含了一个自定义的请求首部字段(X-PINGOTHER: pingpong)。另外,该请求的 Content-Type 为 application/xml。因此,该请求需要首先发起“预检请求”。</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/16753/preflight_correct.png" style="height: 553px; width: 521px;"></p>
+
+<pre class="notranslate">OPTIONS /resources/post-here/ HTTP/1.1
+Host: bar.other
+User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
+Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
+Accept-Language: en-us,en;q=0.5
+Accept-Encoding: gzip,deflate
+Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
+Connection: keep-alive
+Origin: http://foo.example
+Access-Control-Request-Method: POST
+Access-Control-Request-Headers: X-PINGOTHER, Content-Type
+
+
+HTTP/1.1 200 OK
+Date: Mon, 01 Dec 2008 01:15:39 GMT
+Server: Apache/2.0.61 (Unix)
+Access-Control-Allow-Origin: http://foo.example
+Access-Control-Allow-Methods: POST, GET, OPTIONS
+Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
+Access-Control-Max-Age: 86400
+Vary: Accept-Encoding, Origin
+Content-Encoding: gzip
+Content-Length: 0
+Keep-Alive: timeout=2, max=100
+Connection: Keep-Alive
+Content-Type: text/plain</pre>
+
+<p>预检请求完成之后,发送实际请求:</p>
+
+<pre class="notranslate"><code>POST /resources/post-here/ HTTP/1.1
+Host: bar.other
+User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
+Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
+Accept-Language: en-us,en;q=0.5
+Accept-Encoding: gzip,deflate
+Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
+Connection: keep-alive
+X-PINGOTHER: pingpong
+Content-Type: text/xml; charset=UTF-8
+Referer: http://foo.example/examples/preflightInvocation.html
+Content-Length: 55
+Origin: http://foo.example
+Pragma: no-cache
+Cache-Control: no-cache
+
+&lt;?xml version="1.0"?&gt;&lt;person&gt;&lt;name&gt;Arun&lt;/name&gt;&lt;/person&gt;
+
+
+HTTP/1.1 200 OK
+Date: Mon, 01 Dec 2008 01:15:40 GMT
+Server: Apache/2.0.61 (Unix)
+Access-Control-Allow-Origin: http://foo.example
+Vary: Accept-Encoding, Origin
+Content-Encoding: gzip
+Content-Length: 235
+Keep-Alive: timeout=2, max=99
+Connection: Keep-Alive
+Content-Type: text/plain
+
+[Some GZIP'd payload]</code></pre>
+
+<p>浏览器检测到,从 JavaScript 中发起的请求需要被预检。从上面的报文中,我们看到,第 1~12 行发送了一个使用 <code>OPTIONS 方法的“</code>预检请求<code>”。</code> OPTIONS 是 HTTP/1.1 协议中定义的方法,用以从服务器获取更多信息。该方法不会对服务器资源产生影响。 预检请求中同时携带了下面两个首部字段:</p>
+
+<pre class="notranslate"><code>Access-Control-Request-Method: POST
+Access-Control-Request-Headers: X-PINGOTHER, Content-Type</code></pre>
+
+<p>首部字段 {{HTTPHeader("Access-Control-Request-Method")}} 告知服务器,实际请求将使用 POST 方法。首部字段 {{HTTPHeader("Access-Control-Request-Headers")}} 告知服务器,实际请求将携带两个自定义请求首部字段:<code>X-PINGOTHER</code> 与 <code>Content-Type</code>。服务器据此决定,该实际请求是否被允许。</p>
+
+<p>第14~26 行为预检请求的响应,表明服务器将接受后续的实际请求。重点看第 17~20 行:</p>
+
+<pre class="notranslate"><code>Access-Control-Allow-Origin: http://foo.example
+Access-Control-Allow-Methods: POST, GET, OPTIONS
+Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
+Access-Control-Max-Age: 86400</code></pre>
+
+<p><font face="Open Sans, Arial, sans-serif">首部字段</font><code><font face="Open Sans, Arial, sans-serif"> </font>Access-Control-Allow-Methods </code>表明服务器允许客户端使用<code> </code><code>POST,</code> <code>GET </code>和 <code>OPTIONS</code> 方法发起请求。该字段与 <a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7" title="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7">HTTP/1.1 Allow: response header</a> 类似,但仅限于在需要访问控制的场景中使用。</p>
+
+<p>首部字段 <code>Access-Control-Allow-Headers </code>表明服务器允许请求中携带字段 <code><code>X-PINGOTHER </code></code>与<code><code> Content-Type</code></code>。<font face="Open Sans, Arial, sans-serif">与</font><code><code><font face="Open Sans, Arial, sans-serif"> </font></code></code><code>Access-Control-Allow-Methods </code>一样,<code><code>Access-Control-Allow-Headers</code></code> 的值为逗号分割的列表。</p>
+
+<p>最后,首部字段 <code>Access-Control-Max-Age</code> 表明该响应的有效时间为 86400 秒,也就是 24 小时。在有效时间内,浏览器无须为同一请求再次发起预检请求。请注意,浏览器自身维护了一个最大有效时间,如果该首部字段的值超过了最大有效时间,将不会生效。</p>
+
+<h4 id="预检请求与重定向">预检请求与重定向</h4>
+
+<p>大多数浏览器不支持针对于预检请求的重定向。如果一个预检请求发生了重定向,浏览器将报告错误:</p>
+
+<blockquote>
+<p>The request was redirected to 'https://example.com/foo', which is disallowed for cross-origin requests that require preflight</p>
+</blockquote>
+
+<blockquote>
+<p>Request requires preflight, which is disallowed to follow cross-origin redirect</p>
+</blockquote>
+
+<p>CORS 最初要求该行为,不过<a href="https://github.com/whatwg/fetch/commit/0d9a4db8bc02251cc9e391543bb3c1322fb882f2">在后续的修订中废弃了这一要求</a>。</p>
+
+<p>在浏览器的实现跟上规范之前,有两种方式规避上述报错行为:</p>
+
+<ul>
+ <li>在服务端去掉对预检请求的重定向;</li>
+ <li>将实际请求变成一个简单请求。</li>
+</ul>
+
+<p>如果上面两种方式难以做到,我们仍有其他办法:</p>
+
+<ul>
+ <li>发出一个简单请求(使用  <a href="/en-US/docs/Web/API/Response/url">Response.url</a> 或 <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseURL">XHR.responseURL</a>)以判断真正的预检请求会返回什么地址。</li>
+ <li>发出另一个请求(真正的请求),使用在上一步通过<a href="https://developer.mozilla.org/en-US/docs/Web/API/Response/url">Response.url</a> 或 <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseURL">XMLHttpRequest.responseURL</a>获得的URL。</li>
+</ul>
+
+<p>不过,如果请求是由于存在 Authorization 字段而引发了预检请求,则这一方法将无法使用。这种情况只能由服务端进行更改。</p>
+
+<h3 id="附带身份凭证的请求">附带身份凭证的请求</h3>
+
+<p>{{domxref("XMLHttpRequest")}} 或 <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a> 与 CORS 的一个有趣的特性是,可以基于  <a href="/en-US/docs/Web/HTTP/Cookies">HTTP cookies</a> 和 HTTP 认证信息发送身份凭证。一般而言,对于跨源 {{domxref("XMLHttpRequest")}} 或 <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a> 请求,浏览器<strong>不会</strong>发送身份凭证信息。如果要发送凭证信息,需要设置 <code><a class="internal" href="/en/DOM/XMLHttpRequest" title="En/XMLHttpRequest">XMLHttpRequest</a> </code>的某个特殊标志位。</p>
+
+<p>本例中,http://foo.example 的某脚本向 http://bar.other 发起一个GET 请求,并设置 Cookies:</p>
+
+<pre id="line1"><code>var invocation = new XMLHttpRequest();
+var url = 'http://bar.other/resources/credentialed-content/';
+
+function callOtherDomain(){
+ if(invocation) {
+ invocation.open('GET', url, true);
+ invocation.withCredentials = true;
+ invocation.onreadystatechange = handler;
+ invocation.send();
+ }
+}</code></pre>
+
+<p>第 7 行将 <code><a class="internal" href="/en/DOM/XMLHttpRequest" title="En/XMLHttpRequest">XMLHttpRequest</a> </code>的 <code>withCredentials</code> 标志设置为 <code>true</code>,从而向服务器发送 Cookies。因为这是一个简单 GET 请求,所以浏览器不会对其发起“预检请求”。但是,如果服务器端的响应中未携带 <code>Access-Control-Allow-Credentials: true</code> ,浏览器将不会把响应内容返回给请求的发送者。</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/17213/cred-req-updated.png" style="height: 490px; width: 1023px;"></p>
+
+<p>客户端与服务器端交互示例如下:</p>
+
+<pre class="notranslate"><code>GET /resources/access-control-with-credentials/ HTTP/1.1
+Host: bar.other
+User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
+Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
+Accept-Language: en-us,en;q=0.5
+Accept-Encoding: gzip,deflate
+Connection: keep-alive
+Referer: http://foo.example/examples/credential.html
+Origin: http://foo.example
+Cookie: pageAccess=2
+
+
+HTTP/1.1 200 OK
+Date: Mon, 01 Dec 2008 01:34:52 GMT
+Server: Apache/2
+Access-Control-Allow-Origin: http://foo.example
+Access-Control-Allow-Credentials: true
+Cache-Control: no-cache
+Pragma: no-cache
+Set-Cookie: pageAccess=3; expires=Wed, 31-Dec-2008 01:34:53 GMT
+Vary: Accept-Encoding, Origin
+Content-Encoding: gzip
+Content-Length: 106
+Keep-Alive: timeout=2, max=100
+Connection: Keep-Alive
+Content-Type: text/plain
+
+
+[text/plain payload]</code></pre>
+
+<p>即使第 10 行指定了 Cookie 的相关信息,但是,如果 bar.other 的响应中缺失 {{HTTPHeader("Access-Control-Allow-Credentials")}}<code>: true</code>(第 17 行),则响应内容不会返回给请求的发起者。</p>
+
+<h4 id="附带身份凭证的请求与通配符">附带身份凭证的请求与通配符</h4>
+
+<p>对于附带身份凭证的请求,服务器不得设置 <code>Access-Control-Allow-Origin</code> 的值为“<code>*</code>”。</p>
+
+<p>这是因为请求的首部中携带了 <code>Cookie</code> 信息,如果 <code>Access-Control-Allow-Origin</code> 的值为“<code>*</code>”,请求将会失败。而将 <code>Access-Control-Allow-Origin</code> 的值设置为 <code>http://foo.example</code>,则请求将成功执行。</p>
+
+<p>另外,响应首部中也携带了 Set-Cookie 字段,尝试对 Cookie 进行修改。如果操作失败,将会抛出异常。</p>
+
+<h4 id="第三方_cookies">第三方 cookies</h4>
+
+<p>注意在 CORS 响应中设置的 cookies 适用一般性第三方 cookie 策略。在上面的例子中,页面是在 `foo.example` 加载,但是第 20 行的 cookie 是被 `bar.other` 发送的,如果用户设置其浏览器拒绝所有第三方 cookies,那么将不会被保存。</p>
+
+<h2 id="HTTP_响应首部字段">HTTP 响应首部字段</h2>
+
+<p>本节列出了规范所定义的响应首部字段。上一小节中,我们已经看到了这些首部字段在实际场景中是如何工作的。</p>
+
+<h3 id="Access-Control-Allow-Origin">Access-Control-Allow-Origin</h3>
+
+<p>响应首部中可以携带一个 {{HTTPHeader("Access-Control-Allow-Origin")}} 字段,其语法如下:</p>
+
+<pre class="notranslate">Access-Control-Allow-Origin: &lt;origin&gt; | *
+</pre>
+
+<p>其中,origin 参数的值指定了允许访问该资源的外域 URI。对于不需要携带身份凭证的请求,服务器可以指定该字段的值为通配符,表示允许来自所有域的请求。</p>
+
+<p>例如,下面的字段值将允许来自 http://mozilla.com 的请求:</p>
+
+<pre class="notranslate">Access-Control-Allow-Origin: <span class="plain">http://mozilla.com</span></pre>
+
+<p>如果服务端指定了具体的域名而非“*”,那么响应首部中的 Vary 字段的值必须包含 Origin。这将告诉客户端:服务器对不同的源站返回不同的内容。</p>
+
+<h3 id="Access-Control-Expose-Headers">Access-Control-Expose-Headers</h3>
+
+<p>译者注:在跨源访问时,XMLHttpRequest对象的getResponseHeader()方法只能拿到一些最基本的响应头,Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma,如果要访问其他头,则需要服务器设置本响应头。</p>
+
+<p>{{HTTPHeader("Access-Control-Expose-Headers")}} 头让服务器把允许浏览器访问的头放入白名单,例如:</p>
+
+<pre class="notranslate">Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header
+</pre>
+
+<p>这样浏览器就能够通过getResponseHeader访问<code>X-My-Custom-Header</code>和 <code>X-Another-Custom-Header</code> 响应头了。</p>
+
+<h3 id="Access-Control-Max-Age">Access-Control-Max-Age</h3>
+
+<p>{{HTTPHeader("Access-Control-Max-Age")}} 头指定了preflight请求的结果能够被缓存多久,请参考本文在前面提到的preflight例子。</p>
+
+<pre class="notranslate">Access-Control-Max-Age: &lt;delta-seconds&gt;
+</pre>
+
+<p><code>delta-seconds</code> 参数表示preflight请求的结果在多少秒内有效。</p>
+
+<h3 id="Access-Control-Allow-Credentials">Access-Control-Allow-Credentials</h3>
+
+<p>{{HTTPHeader("Access-Control-Allow-Credentials")}} 头指定了当浏览器的<code>credentials</code>设置为true时是否允许浏览器读取response的内容。当用在对preflight预检测请求的响应中时,它指定了实际的请求是否可以使用<code>credentials</code>。请注意:简单 GET 请求不会被预检;如果对此类请求的响应中不包含该字段,这个响应将被忽略掉,并且浏览器也不会将相应内容返回给网页。</p>
+
+<pre class="notranslate">Access-Control-Allow-Credentials: true
+</pre>
+
+<p>上文已经讨论了<a href="#Requests_with_credentials">附带身份凭证的请求</a>。</p>
+
+<h3 id="Access-Control-Allow-Methods">Access-Control-Allow-Methods</h3>
+
+<p>{{HTTPHeader("Access-Control-Allow-Methods")}} 首部字段用于预检请求的响应。其指明了实际请求所允许使用的 HTTP 方法。</p>
+
+<pre class="notranslate">Access-Control-Allow-Methods: &lt;method&gt;[, &lt;method&gt;]*
+</pre>
+
+<p>相关示例见<a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS$edit#Preflighted_requests">这里</a>。</p>
+
+<h3 id="Access-Control-Allow-Headers">Access-Control-Allow-Headers</h3>
+
+<p>{{HTTPHeader("Access-Control-Allow-Headers")}} 首部字段用于预检请求的响应。其指明了实际请求中允许携带的首部字段。</p>
+
+<pre class="notranslate">Access-Control-Allow-Headers: &lt;field-name&gt;[, &lt;field-name&gt;]*
+</pre>
+
+<h2 id="HTTP_请求首部字段">HTTP 请求首部字段</h2>
+
+<p>本节列出了可用于发起跨源请求的首部字段。请注意,这些首部字段无须手动设置。 当开发者使用 XMLHttpRequest 对象发起跨源请求时,它们已经被设置就绪。</p>
+
+<h3 id="Origin">Origin</h3>
+
+<p>{{HTTPHeader("Origin")}} 首部字段表明预检请求或实际请求的源站。</p>
+
+<pre class="notranslate">Origin: &lt;origin&gt;
+</pre>
+
+<p>origin 参数的值为源站 URI。它不包含任何路径信息,只是服务器名称。</p>
+
+<div class="note"><strong>Note:</strong> 有时候将该字段的值设置为空字符串是有用的,例如,当源站是一个 data URL 时。</div>
+
+<p>注意,在所有访问控制请求(Access control request)中,{{HTTPHeader("Origin")}} 首部字段<strong>总是</strong>被发送。</p>
+
+<h3 id="Access-Control-Request-Method">Access-Control-Request-Method</h3>
+
+<p>{{HTTPHeader("Access-Control-Request-Method")}} 首部字段用于预检请求。其作用是,将实际请求所使用的 HTTP 方法告诉服务器。</p>
+
+<pre class="notranslate">Access-Control-Request-Method: &lt;method&gt;
+</pre>
+
+<p>相关示例见<a href="#Preflighted_requests">这里</a>。</p>
+
+<h3 id="Access-Control-Request-Headers">Access-Control-Request-Headers</h3>
+
+<p>{{HTTPHeader("Access-Control-Request-Headers")}} 首部字段用于预检请求。其作用是,将实际请求所携带的首部字段告诉服务器。</p>
+
+<pre class="notranslate">Access-Control-Request-Headers: &lt;field-name&gt;[, &lt;field-name&gt;]*
+</pre>
+
+<p>相关示例见<a href="#">这里</a>。</p>
+
+<h2 id="规范">规范</h2>
+
+<table>
+ <tbody>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('Fetch', '#cors-protocol', 'CORS')}}</td>
+ <td>{{Spec2('Fetch')}}</td>
+ <td>New definition; supplants CORS specification.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('CORS')}}</td>
+ <td>{{Spec2('CORS')}}</td>
+ <td>Initial definition.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="浏览器兼容性">浏览器兼容性</h2>
+
+<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>
+
+<p>{{Compat("http.headers.Access-Control-Allow-Origin")}}</p>
+
+<h3 id="注">注</h3>
+
+<ul>
+ <li>IE 10 提供了对规范的完整支持,但在较早版本(8 和 9)中,CORS 机制是借由 XDomainRequest 对象完成的。</li>
+ <li>Firefox 3.5 引入了对 XMLHttpRequests 和 Web 字体的跨源支持(但最初的实现并不完整,这在后续版本中得到完善);Firefox 7 引入了对 WebGL 贴图的跨源支持;Firefox 9 引入了对 drawImage 的跨源支持。</li>
+</ul>
+
+<h2 id="参见">参见</h2>
+
+<ul>
+ <li><a href="http://arunranga.com/examples/access-control/">Code Samples Showing <code>XMLHttpRequest</code> and Cross-Origin Resource Sharing</a></li>
+ <li><a href="/en-US/docs/Web/HTTP/Server-Side_Access_Control">Cross-Origin Resource Sharing From a Server-Side Perspective (PHP, etc.)</a></li>
+ <li><a href="http://www.w3.org/TR/cors/">Cross-Origin Resource Sharing specification</a></li>
+ <li>{{domxref("XMLHttpRequest")}}</li>
+ <li><a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a></li>
+ <li><a href="http://www.kendoui.com/blogs/teamblog/posts/11-10-03/using_cors_with_all_modern_browsers.aspx">Using CORS with All (Modern) Browsers</a></li>
+ <li><a href="http://www.html5rocks.com/en/tutorials/cors/">Using CORS - HTML5 Rocks</a></li>
+</ul>
+
+<p>{{ languages( { "ja": "ja/HTTP_access_control" } ) }}</p>