Types of CORS Requests

CORS requests can be classified primarily into two types: simple requests and preflight requests. Each type has specific characteristics and serves different purposes within the CORS framework.

1. Simple Requests

Simple requests are certain kinds of requests that are considered safe enough not to require explicit CORS preflight approval. These requests include:

Characteristics:

  • Use of HTTP methods: GET, POST, or HEAD.
  • Only certain headers are allowed, such as Accept, Content-Language, Content-Type with certain values, and a few others.
  • No custom headers or ReadableStream objects in requests.

Examples:

  • A GET request for a public image or a JSON file from a different domain.
  • A POST request submitting a form to a server from a different domain, where the Content-Type is application/x-www-form-urlencoded, multipart/form-data, or text/plain.

These requests are considered 'simple' because they don't significantly differ from typical HTTP requests and are unlikely to pose a security risk.

2. Preflight Requests

Preflight requests are used for more complex or potentially risky requests, providing an additional layer of security. These include:

Characteristics:

  • Involve HTTP methods other than GET, POST, or HEAD, such as PUT, DELETE, or CONNECT.
  • Use of custom headers or non-standard content types.
  • Requests that might modify data on the server.

Detailed Explanation and Examples:

  • Before the actual request is made, the browser sends an OPTIONS request to the server hosting the cross-origin resource. This OPTIONS request includes headers that indicate the HTTP method and headers that will be used in the actual request.
  • The server responds with whether these methods and headers are acceptable. This response includes headers like - Access-Control-Allow-Methods and Access-Control-Allow-Headers. If the server's response indicates that the actual request is acceptable, the browser then proceeds to send it.

Example:

  • A PUT request to update a record in a database hosted on a different domain, where the request includes custom headers like X-My-Custom-Header.

Preflight requests are essential to CORS, ensuring that the server explicitly permits more complex or potentially risky cross-origin requests before they are made. This mechanism helps maintain web security while still allowing the necessary flexibility for modern web applications.