MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • What requests use CORS?
  • Functional overview
  • Examples of access control scenarios
  • The HTTP response headers
  • The HTTP request headers
  1. 2nd Month
  2. Week 5
  3. REST - Representational State Transfer

Cross-Origin Resource Sharing (CORS)

PreviousThe Fetch APINextWeekly Review

Last updated 1 year ago

Cross-Origin Resource Sharing () is an -header based mechanism that allows a server to indicate any (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server 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.

An example of a cross-origin request: the front-end JavaScript code served from https://domain-a.com uses to make a request for https://domain-b.com/data.json.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the follow the . 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.

Diagrammatic representation of CORS mechanism

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

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

Subsequent sections discuss scenarios, as well as provide a breakdown of the HTTP headers used.

A simple request is one that meets all the following conditions:

  • One of the allowed methods:

    • application/x-www-form-urlencoded

    • multipart/form-data

    • text/plain

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 content 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();

Copy to Clipboard

This operation performs a simple exchange between the client and the server, using CORS headers to handle the privileges:

Let's look at what the browser will send to the server in this case:

GET /resources/public-data/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
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
Origin: https://foo.example

Copy to Clipboard

Now let's see how the server responds:

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 00:23:53 GMT
Server: Apache/2
Access-Control-Allow-Origin: *
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/xml

[…XML Data…]

Copy to Clipboard

Access-Control-Allow-Origin: *

Copy to Clipboard

Access-Control-Allow-Origin: https://foo.example

Copy to Clipboard

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

const xhr = new XMLHttpRequest();
xhr.open("POST", "https://bar.other/doc");
xhr.setRequestHeader("X-PINGOTHER", "pingpong");
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.onreadystatechange = handler;
xhr.send("<person><name>Arun</name></person>");

Copy to Clipboard

The example above creates an XML body to send with the POST request. Also, a non-standard HTTP X-PINGOTHER request header is set. Such headers are not part of HTTP/1.1, but are generally useful to web applications. Since the request uses a Content-Type of text/xml, and since a custom header is set, this request is preflighted.

Note: 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 and server. The first exchange is the preflight request/response:

OPTIONS /doc HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
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
Origin: https://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type

HTTP/1.1 204 No Content
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2
Access-Control-Allow-Origin: https://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
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive

Copy to Clipboard

Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type

Copy to Clipboard

Lines 12 - 21 above are the response that the server returns, which indicate that the request method (POST) and request headers (X-PINGOTHER) are acceptable. Let's have a closer look at lines 15-18:

Access-Control-Allow-Origin: https://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400

Copy to Clipboard

The server also sends Access-Control-Allow-Headers with a value of "X-PINGOTHER, Content-Type", confirming that these are permitted headers to be used with the actual request. Like Access-Control-Allow-Methods, Access-Control-Allow-Headers is a comma-separated list of acceptable headers.

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

POST /doc HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
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
X-PINGOTHER: pingpong
Content-Type: text/xml; charset=UTF-8
Referer: https://foo.example/examples/preflightInvocation.html
Content-Length: 55
Origin: https://foo.example
Pragma: no-cache
Cache-Control: no-cache

<person><name>Arun</name></person>

HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:40 GMT
Server: Apache/2
Access-Control-Allow-Origin: https://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 XML payload]

Copy to Clipboard

Preflighted requests and redirects

Not all browsers currently support following redirects after a preflighted request. If a redirect occurs after such a request, some browsers currently will report an error message such as the following:

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

  • Change the server-side behavior to avoid the preflight and/or to avoid the redirect

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

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

However, if the request is one that triggers a preflight due to 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 to work around it at all unless you have control over the server the request is being made to.

Note: When making credentialed requests to a different domain, third-party cookie policies will still apply. The policy is always enforced regardless of any setup on the server and the client as described in this chapter.

In this example, content originally loaded from https://foo.example makes a simple GET request to a resource on https://bar.other which sets Cookies. Content on foo.example might contain JavaScript like this:

const invocation = new XMLHttpRequest();
const url = "https://bar.other/resources/credentialed-content/";

function callOtherDomain() {
  if (invocation) {
    invocation.open("GET", url, true);
    invocation.withCredentials = true;
    invocation.onreadystatechange = handler;
    invocation.send();
  }
}

Copy to Clipboard

Here is a sample exchange between client and server:

GET /resources/credentialed-content/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
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: https://foo.example/examples/credential.html
Origin: https://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: https://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]

Copy to Clipboard

Preflight requests and credentials

CORS-preflight requests must never include credentials. The response to a preflight request must specify Access-Control-Allow-Credentials: true to indicate that the actual request can be made with credentials.

Credentialed requests and wildcards

When responding to a credentialed request:

  • The server must not specify the "*" wildcard for the Access-Control-Allow-Origin response-header value, but must instead specify an explicit origin; for example: Access-Control-Allow-Origin: https://example.com

  • The server must not specify the "*" wildcard for the Access-Control-Allow-Headers response-header value, but must instead specify an explicit list of header names; for example, Access-Control-Allow-Headers: X-PINGOTHER, Content-Type

  • The server must not specify the "*" wildcard for the Access-Control-Allow-Methods response-header value, but must instead specify an explicit list of method names; for example, Access-Control-Allow-Methods: POST, GET

  • The server must not specify the "*" wildcard for the Access-Control-Expose-Headers response-header value, but must instead specify an explicit list of header names; for example, Access-Control-Expose-Headers: Content-Encoding, Kuma-Revision

If a request includes a credential (most commonly a Cookie header) and the response includes an Access-Control-Allow-Origin: * header (that is, with the wildcard), the browser will block access to the response, and report a CORS error in the devtools console.

But if a request does include a credential (like the Cookie header) and the response includes an actual origin rather than the wildcard (like, for example, Access-Control-Allow-Origin: https://example.com), then the browser will allow access to the response from the specified origin.

Also note that any Set-Cookie response header in a response would not set a cookie if the Access-Control-Allow-Origin value in that response is the "*" wildcard rather an actual origin.

Third-party cookies

Note that cookies set in CORS responses are subject to normal third-party cookie policies. In the example above, the page is loaded from foo.example but the cookie on line 19 is sent by bar.other, and would thus not be saved if the user's browser is configured to reject all third-party cookies.

Cookie in the request (line 10) may also be suppressed in normal third-party cookie policies. The enforced cookie policy may therefore nullify the capability described in this chapter, effectively preventing you from making credentialed requests whatsoever.

This section lists the HTTP response headers that servers return for access control requests as defined by the Cross-Origin Resource Sharing specification. The previous section gives an overview of these in action.

Access-Control-Allow-Origin: <origin> | *

Copy to Clipboard

Access-Control-Allow-Origin specifies either a single origin which tells browsers to allow that origin to access the resource; or else — for requests without credentials — the "*" wildcard tells browsers to allow any origin to access the resource.

For example, to allow code from the origin https://mozilla.org to access the resource, you can specify:

Access-Control-Allow-Origin: https://mozilla.org
Vary: Origin

Copy to Clipboard

Access-Control-Expose-Headers: <header-name>[, <header-name>]*

Copy to Clipboard

For example, the following:

Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header

Copy to Clipboard

…would allow the X-My-Custom-Header and X-Another-Custom-Header headers to be exposed to the browser.

Access-Control-Max-Age: <delta-seconds>

Copy to Clipboard

The delta-seconds parameter indicates the number of seconds the results can be cached.

Access-Control-Allow-Credentials: true

Copy to Clipboard

Access-Control-Allow-Methods: <method>[, <method>]*

Copy to Clipboard

Access-Control-Allow-Headers: <header-name>[, <header-name>]*

Copy to Clipboard

Origin: <origin>

Copy to Clipboard

The origin is a URL indicating the server from which the request is initiated. It does not include any path information, only the server name.

Note: The origin value can be null.

Access-Control-Request-Method: <method>

Copy to Clipboard

Access-Control-Request-Headers: <field-name>[, <field-name>]*

Copy to Clipboard

The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers. Modern browsers use CORS in APIs such as XMLHttpRequest or to mitigate the risks of cross-origin HTTP requests.

This can enable cross-origin HTTP requests for:

Invocations of the or , as discussed above.

Web Fonts (for cross-domain font usage in @font-face within CSS),

.

Images/video frames drawn to a canvas using .

The Cross-Origin Resource Sharing standard works by adding new that let servers describe which origins are permitted to read that information from a web browser. Additionally, for HTTP request methods that can cause side-effects on server data (in particular, HTTP methods other than , or with certain ), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with the HTTP request method, and then, upon "approval" from the server, sending the actual request. Servers can also inform clients whether "credentials" (such as and ) should be sent with requests.

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

Some requests don't trigger a . Those are called simple requests from the obsolete , though the (which now defines CORS) doesn't use that term.

The motivation is that the element from HTML 4.0 (which predates cross-site and ) can submit simple requests to any origin, so anyone writing a server must already be protecting against (CSRF). Under this assumption, the server doesn't have to opt-in (by responding to a preflight request) to receive any request that looks like a form submission, since the threat of CSRF is no worse than that of form submission. However, the server still must opt-in using to share the response with the script.

Apart from the headers automatically set by the user agent (for example, , , or ), the only headers which are allowed to be manually set are , which are:

(please note the additional requirements below)

(only with a ; e.g., bytes=256- or bytes=127-255)

Note: Firefox has not implemented Range as a safelisted request-header yet. See .

The only type/subtype combinations allowed for the specified in the header are:

If the request is made using an object, no event listeners are registered on the object returned by the property used in the request; that is, given an instance xhr, no code has called xhr.upload.addEventListener() to add an event listener to monitor the upload.

No object is used in the request.

Note: WebKit Nightly and Safari Technology Preview place additional restrictions on the values allowed in the , , and headers. If any of those headers have "nonstandard" values, WebKit/Safari does not consider the request to be a "simple request". What values WebKit/Safari consider "nonstandard" is not documented, except in the following WebKit bugs:

Diagram of simple CORS GET request

The request header of note is , which shows that the invocation is coming from https://foo.example.

In response, the server returns a header with Access-Control-Allow-Origin: *, which means that the resource can be accessed by any origin.

This pattern of the and headers is the simplest use of the access control protocol. If the resource owners at https://bar.other wished to restrict access to the resource to requests only from https://foo.example (i.e., no domain other than https://foo.example can access the resource in a cross-origin manner), they would send:

Note: When responding to a request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the "*" wildcard.

Unlike , for "preflighted" requests the browser first sends an HTTP request using the method to the resource on the other origin, in order to determine if the actual request is safe to send. Such cross-origin requests are preflighted since they may have implications for user data.

Diagram of a request that is preflighted

Lines 1 - 10 above represent the preflight request with the method. The browser determines that it needs to send this based on the request parameters that the JavaScript code snippet above was using, so that the server can respond whether it is acceptable to send the request with the actual request parameters. OPTIONS is an HTTP/1.1 method that is used to determine further information from servers, and is a method, meaning that it can't be used to change the resource. Note that along with the OPTIONS request, two other request headers are sent (lines 9 and 10 respectively):

The header notifies the server as part of a preflight request that when the actual request is sent, it will do so with a POST request method. The header notifies the server that when the actual request is sent, it will do so with X-PINGOTHER and Content-Type custom headers. Now the server has an opportunity to determine whether it can accept a request under these conditions.

The server responds with Access-Control-Allow-Origin: https://foo.example, restricting access to the requesting origin domain only. It also responds with Access-Control-Allow-Methods, which says that POST and GET are valid methods to query the resource in question (this header is similar to the response header, but used strictly within the context of access control).

Finally, gives the value in seconds for how long the response to the preflight request can be cached without sending another preflight request. The default value is 5 seconds. In the present case, the max age is 86400 seconds (= 24 hours). Note that each browser has a that takes precedence when the Access-Control-Max-Age exceeds it.

The request was redirected to '', which is disallowed for cross-origin requests that require preflight. Request requires preflight, which is disallowed to follow cross-origin redirects.

The CORS protocol originally required that behavior but . However, not all browsers have implemented the change, and thus still exhibit the originally required behavior.

Change the request such that it is a that doesn't cause a preflight

Make a (using for the Fetch API, or ) to determine what URL the real preflighted request would end up at.

The most interesting capability exposed by both or and CORS is the ability to make "credentialed" requests that are aware of and HTTP Authentication information. By default, in cross-origin XMLHttpRequest or invocations, browsers will not send credentials. A specific flag has to be set on the XMLHttpRequest object or the constructor when it is invoked.

Line 7 shows the flag on that has to be set in order to make the invocation with Cookies, namely the withCredentials boolean value. By default, the invocation is made without Cookies. Since this is a simple GET request, it is not preflighted but the browser will reject any response that does not have the : true header, and not make the response available to the invoking web content.

Diagram of a simple GET request with Access-Control-Allow-Credentials

Although line 10 contains the Cookie destined for the content on https://bar.other, if bar.other did not respond with an : true (line 16), the response would be ignored and not made available to the web content.

Note: Some enterprise authentication services require that TLS client certificates be sent in preflight requests, in contravention of the specification.

Firefox 87 allows this non-compliant behavior to be enabled by setting the preference: network.cors_preflight.allow_client_cert to true (). Chromium-based browsers currently always send TLS client certificates in CORS preflight requests ().

Cookie policy around the attribute would apply.

A returned resource may have one header with the following syntax:

If the server specifies a single origin (that may dynamically change based on the requesting origin as part of an allowlist) rather than the "*" wildcard, then the server should also include Origin in the response header to indicate to clients that server responses will differ based on the value of the request header.

The header adds the specified headers to the allowlist that JavaScript (such as ) in browsers is allowed to access.

The header indicates how long the results of a preflight request can be cached. For an example of a preflight request, see the above examples.

The header indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple GET requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content.

are discussed above.

The header specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. The conditions under which a request is preflighted are discussed above.

An example of a is given above, including an example which sends this header to the browser.

The header is used in response to a to indicate which HTTP headers can be used when making the actual request. This header is the server side response to the browser's header.

This section lists headers that clients may use when issuing HTTP requests in order to make use of the cross-origin sharing feature. Note that these headers are set for you when making invocations to servers. Developers using cross-origin capability do not have to set any cross-origin sharing request headers programmatically.

The header indicates the origin of the cross-origin access request or preflight request.

Note that in any access control request, the header is always sent.

The is used when issuing a preflight request to let the server know what HTTP method will be used when the actual request is made.

Examples of this usage can be

The header is used when issuing a preflight request to let the server know what HTTP headers will be used when the actual request is made (such as with ). This browser-side header will be answered by the complementary server-side header of .

Examples of this usage can be .

2️⃣
Fetch
What requests use CORS?
cross-origin sharing standard
XMLHttpRequest
Fetch APIs
so that servers can deploy TrueType fonts that can only be loaded cross-origin and used by websites that are permitted to do so.
WebGL textures
drawImage()
CSS Shapes from images.
Functional overview
HTTP headers
GET
POST
MIME types
OPTIONS
Cookies
HTTP Authentication
Examples of access control scenarios
XMLHttpRequest
Simple requests
CORS preflight
CORS spec
Fetch spec
<form>
XMLHttpRequest
fetch
cross-site request forgery
Access-Control-Allow-Origin
GET
HEAD
POST
Connection
User-Agent
the other headers defined in the Fetch spec as a forbidden header name
those which the Fetch spec defines as a CORS-safelisted request-header
Accept
Accept-Language
Content-Language
Content-Type
Range
simple range header value
bug 1733981
media type
Content-Type
XMLHttpRequest
XMLHttpRequest.upload
XMLHttpRequest
ReadableStream
Accept
Accept-Language
Content-Language
Require preflight for non-standard CORS-safelisted request headers Accept, Accept-Language, and Content-Language
Allow commas in Accept, Accept-Language, and Content-Language request headers for simple CORS
Switch to a blacklist model for restricted Accept headers in simple CORS requests
Origin
Access-Control-Allow-Origin
Origin
Access-Control-Allow-Origin
credentialed requests
Preflighted requests
simple requests
OPTIONS
OPTIONS
safe
Access-Control-Request-Method
Access-Control-Request-Headers
Allow
Access-Control-Max-Age
maximum internal value
https://example.com/foo
was subsequently changed to no longer require it
simple request
simple request
Response.url
XMLHttpRequest.responseURL
Requests with credentials
XMLHttpRequest
Fetch
HTTP cookies
Fetch
Request
XMLHttpRequest
Access-Control-Allow-Credentials
Access-Control-Allow-Credentials
Fetch
Firefox bug 1511151
Chrome bug 775438
SameSite
The HTTP response headers
Access-Control-Allow-Origin
Access-Control-Allow-Origin
Vary
Origin
Access-Control-Expose-Headers
Access-Control-Expose-Headers
getResponseHeader()
Access-Control-Max-Age
Access-Control-Max-Age
Access-Control-Allow-Credentials
Access-Control-Allow-Credentials
Credentialed requests
Access-Control-Allow-Methods
Access-Control-Allow-Methods
preflight request
Access-Control-Allow-Headers
Access-Control-Allow-Headers
preflight request
Access-Control-Request-Headers
The HTTP request headers
XMLHttpRequest
Origin
Origin
Origin
Access-Control-Request-Method
Access-Control-Request-Method
found above.
Access-Control-Request-Headers
Access-Control-Request-Headers
setRequestHeader()
Access-Control-Allow-Headers
found above
CORS
HTTP
origins
XMLHttpRequest
Fetch API
same-origin policy