CORS (Cross-Origin Resource Sharing)

CORS is a mechanism that allows a server to indicate any origins that a server can share its resources with. These origins can be domains, schemes, or ports. This is an HTTP mechanism that enables the transfer of hypermedia documents on the web.

How does CORS work?

  1. Browsers send a pre-flight (pre-check) request that checks if the server will grant access to the request being made.
  2. The browser sends headers that indicate to the server that the cross-origin resource sharing is allowed.
  3. CORS restricts access to HTTP requests that are initiated by scripts and not a user.

Who uses CORS

  • API’s
  • Web Browsers
  • CSS shapes, textures, and Images from another source

Simple Requests

Simple requests don’t need CORS pre-flight if they meet all criteria:

  • Use GET, HEAD, or POST methods
  • Only use certain headers (Accept, Accept-Language, Content-Language, Content-Type)
  • Content-Type must be one of: application/json, multipart/form-data, text/plain
  • No readable stream object used in request

Example

let request = new XMLHttpRequest();
let method = "GET";
let url = "https://v2.jokeapi.dev/joke/Any";
request.open(method, url);
request.send();

Example with headers:

const headers = {
  "Content-Type": "application/json",
  "Authorization": `Bearer 12345`,
  "Access-Control-Allow-Headers": "Content-Type",
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "OPTIONS,PUT,GET",
};
fetch(url, { headers });