Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a VPS to indicate any other origins (domain name, scheme, or port) than its own from which a browser should permit loading of resources. CORS also relies on a mechanism by which browsers make a “preflight” request khổng lồ the hệ thống hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP. method and headers that will be used in the actual request.

Bạn đang xem: Jquery

An example of a cross-origin request: the front-kết thúc JavaScript code served from https://domain-a.com uses XMLHttpRequest lớn make a request for https://domain-b.com/data.json.

For security reasons, browsers restrict cross-origin HTTPhường requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.


The CORS mechanism supports secure cross-origin requests và data transfers between browsers and servers. Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch lớn mitigate the risks of cross-origin HTTPhường. requests.

Who should read this article?

Everyone, really.

More specifically, this article is for web administrators, hệ thống nguyenminhchau.coms, và front-over nguyenminhchau.coms. Modern browsers handle the client side of cross-origin sharing, including headers & policy enforcement. But the CORS standard means servers have lớn handle new request và response headers.

What requests use CORS?

This cross-origin sharing standard can enable cross-site HTTPhường requests for:

This article is a general discussion of Cross-Origin Resource Sharing và includes a discussion of the necessary HTTP. headers.

Functional overview

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let servers describe which origins are permitted to lớn read that information from a web browser. Additionally, for HTTP request methods that can cause side-effects on hệ thống data (in particular, HTTP methods other than GET, or POST with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the HTTPhường OPTIONS request method, and then, upon "approval" from the hệ thống, sending the actual request. Servers can also insize clients whether "credentials" (such as Cookies and HTTP Authentication) should be sent with requests.

CORS failures result in errors, but for security reasons, specifics about the error are not available lớn JavaScript. All the code knows is that an error occurred. The only way to determine what specifically went wrong is khổng lồ look at the browser"s console for details.

Subsequent sections discuss scenarquả táo, as well as provide a breakdown of the HTTPhường headers used.

Examples of access control scenarios

We present three scenarios that demonstrate how Cross-Origin Resource Sharing works. All these examples use XMLHttpRequest, which can make cross-site requests in any supporting browser.

Simple requests

Some requests don’t trigger a CORS preflight. Those are called “simple requests” in this article, though the Fetch spec (which defines CORS) doesn’t use that term. A “simple request” is one that meets all the following conditions:

One of the allowed methods: Apart from the headers automatically mix by the web1_user agent (for example, Connection, User-Agent, or the other headers defined in the Fetch spec as a “forbidden header name”), the only headers which are allowed khổng lồ be manually set are those which the Fetch spec defines as a “CORS-safelisted request-header”, which are: The only allowed values for the Content-Type header are: application/x-www-form-urlencoded multipart/form-data text/plain
lưu ý

WebKit Nightly and Safari Technology Pđánh giá place additional restrictions on the values allowed in the Accept, Accept-Language, and Content-Language headers. If any of those headers have ”nonstandard” values, WebKit/Safari does not consider the request khổng lồ be a “simple request”. What values WebKit/Safari consider “nonstandard” is not documented, except in the following WebKit bugs:

No other browsers implement these extra restrictions, because they’re not part of the spec.

For example, suppose web content at https://foo.example wishes to invoke nội dung on domain https://bar.other. Code of this sort might be used in JavaScript deployed on foo.example:

const xhr = new XMLHttpRequest();const url = "https://bar.other/resources/public-data/";xhr.open("GET", url);xhr.onreadystatechange = someHandler;xhr.send();This performs a simple exchange between the client and the VPS, using CORS headers to lớn handle the privileges:


Let"s look at what the browser will sover lớn the VPS in this case, và let"s see how the VPS responds:

GET /resources/public-data/ HTTP/1.1Host: bar.otherUser-Agent: nguyenminhchau.com/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip,deflateConnection: keep-aliveOrigin: https://foo.exampleThe request header of note is Origin, which shows that the invocation is coming from https://foo.example.

Xem thêm: Hướng Dẫn Tạo Usb Boot Với Hiren"S Bootcd Nhanh Chóng, Cách Tạo Usb Ghost, Cách Ghost Máy Tính Bằng Usb

HTTP/1.1 200 OKDate: Mon, 01 Dec 2008 00:23:53 GMTServer: Apache/2Access-Control-Allow-Origin: *Keep-Alive: timeout=2, max=100Connection: Keep-AliveTransfer-Encoding: chunkedContent-Type: application/xml<…XML Data…>In response, the server sends baông xã an Access-Control-Allow-Origin headerwith Access-Control-Allow-Origin: *, which means that the resource can be accessed by any origin.

Access-Control-Allow-Origin: *Thispattern ofthe Origin and Access-Control-Allow-Origin headers is the simplest use of the access control protocol.If the resource owners at https://bar.other wished lớn restrict access lớn the resource to lớn requests only from https://foo.example, (i.e no tên miền other than https://foo.example can access the resource in a cross-site manner) they would send:

Access-Control-Allow-Origin: https://foo.example
Note When responding to lớn a credentialed requests request, the VPS must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the "*" wildcard.

Preflighted requests

Unlượt thích “simple requests” (discussed above), for "preflighted" requests the browser firstsends an HTTPhường request using the OPTIONS method to the resource on the other origin, in order to lớn determine if the actual request is safe khổng lồ skết thúc. Cross-site requests are preflighted lượt thích this since they may have sầu implications to lớn web1_user data.

The following is an example of a request that will be preflighted:

const xhr = new XMLHttpRequest();xhr.open("POST", "https://bar.other/resources/post-here/");xhr.setRequestHeader("X-PINGOTHER", "pingpong");xhr.setRequestHeader("Content-Type", "application/xml");xhr.onreadystatechange = handler;xhr.send("Arun");The example above creates an XML toàn thân to send with the POST request. Also, a non-standard HTTPhường. X-PINGOTHER request header is set. Such headers are not part of HTTP/1.1, but are generally useful to lớn website applications. Since the request uses a Content-Type of application/xml, và since a custom header is mix, this request is preflighted.


cảnh báo

As described below, the actual POST request does not include the Access-Control-Request-* headers; they are needed only for the OPTIONS request.

Let"s look at the full exchange between client và server. The first exchange is the preflight request/response:

OPTIONS /doc HTTP/1.1Host: bar.otherUser-Agent: nguyenminhchau.com/5.0 (Macintosh; Hãng sản xuất Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip,deflateConnection: keep-aliveOrigin: http://foo.exampleAccess-Control-Request-Method: POSTAccess-Control-Request-Headers: X-PINGOTHER, Content-TypeHTTP/1.1 204 No ContentDate: Mon, 01 Dec 2008 01:15:39 GMTServer: Apache/2Access-Control-Allow-Origin: https://foo.exampleAccess-Control-Allow-Methods: POST, GET, OPTIONSAccess-Control-Allow-Headers: X-PINGOTHER, Content-TypeAccess-Control-Max-Age: 86400Vary: Accept-Encoding, OriginKeep-Alive: timeout=2, max=100Connection: Keep-AliveLines 1 - 10 above represent the preflight request with the OPTIONS method. The browser determines that it needs khổng lồ skết thúc this based on the request parameters that the JavaScript code snippet above was using, so that the hệ thống can respond whether it is acceptable khổng lồ sover the request with the actual request parameters. OPTIONS is an HTTP/1.1 method that is used lớn determine further information from servers, & is a safe method, meaning that it can"t be used to change the resource. lưu ý that along with the OPTIONS request, two other request headers are sent (lines 9 & 10 respectively):

Access-Control-Request-Method: POSTAccess-Control-Request-Headers: X-PINGOTHER, Content-TypeThe Access-Control-Request-Method header notifies the VPS as part of a preflight request that when the actual request is sent, it will be sent with a POST request method. The Access-Control-Request-Headers header notifies the VPS that when the actual request is sent, it will be sent with a X-PINGOTHER & Content-Type custom headers. The VPS now has an opportunity to lớn determine whether it wishes to lớn accept a request under these circumstances.

Lines 13 - 22 above are the response that the VPS sends baông xã, which indicatethat the request method (POST) và request headers (X-PINGOTHER) are acceptable. In particular, let"s look at lines 16-19:

Access-Control-Allow-Origin: http://foo.exampleAccess-Control-Allow-Methods: POST, GET, OPTIONSAccess-Control-Allow-Headers: X-PINGOTHER, Content-TypeAccess-Control-Max-Age: 86400The server responds with Access-Control-Allow-Origin: http://foo.example, restricting access to lớn just the requestingorigin domain name. It alsoresponds with Access-Control-Allow-Methods, which says that POST và GET are viable methods lớn query the resource in question (this header is similar to lớn the Allow response header, but used strictly within the context of access control).

The hệ thống also sends Access-Control-Allow-Headers with a value of "X-PINGOTHER, Content-Type", confirming that these are permitted headers khổng lồ be used with the actual request. Like Access-Control-Allow-Methods, Access-Control-Allow-Headers is a comma separated các mục of acceptable headers.

Finally, Access-Control-Max-Age gives the value in seconds for how long the response to the preflight request can be cached for without sending another preflight request. In this case, 86400 seconds is 24 hours. chú ý that each browser has a maximum internal value that takes precedence when the Access-Control-Max-Age is greater.

Once the preflight request is complete, the real request is sent:

POST /doc HTTP/1.1Host: bar.otherUser-Agent: nguyenminhchau.com/5.0 (Macintosh; Hãng Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip,deflateConnection: keep-aliveX-PINGOTHER: pingpongContent-Type: text/xml; charset=UTF-8Referer: https://foo.example/examples/preflightInvocation.htmlContent-Length: 55Origin: https://foo.examplePragma: no-cacheCache-Control: no-cacheperson>name>Arun/name>/person>HTTP/1.1 200 OKDate: Mon, 01 Dec 2008 01:15:40 GMTServer: Apache/2Access-Control-Allow-Origin: https://foo.exampleVary: Accept-Encoding, OriginContent-Encoding: gzipContent-Length: 235Keep-Alive: timeout=2, max=99Connection: Keep-AliveContent-Type: text/plainPreflighted requests và redirectsNot all browsers currently tư vấn following redirects after a preflighted request. If a redirect occurs after a preflighted request, some browsers currently will report an error message such as the following.

The request was redirected lớn "https://example.com/foo", which is disallowed for cross-origin requests that require preflight

Request requires preflight, which is disallowed lớn follow cross-origin redirect

The CORS protocol originally required that behavior but was subsequently changed to no longer require it. However, not all browsers have implemented the change, và so still exhibit the behavior that was originally required.

Until browsers catch up with the spec, you may be able to lớn work around this limitation by doing one or both of the following:

Change the server-side behavior to lớn avoid the preflight and/or to avoid the redirect

If that"s not possible, then another way is to:

Make another request (the “real” request) using the URL you obtained from Response.url or XMLHttpRequest.responseURL in the first step.

Xem thêm: Lịch Thi Thpt Quốc Gia 2018 Từ 25 Đến 27/6, Công Bố Lịch Thi Thpt Quốc Gia 2018

However, if the request is one that triggers a preflight due to lớn the presence of the Authorization header in the request, you won’t be able to work around the limitation using the steps above. And you won’t be able khổng lồ work around it at all unless you have control over the VPS the request is being made to.

Chuyên mục: Lập trình viên