Understanding CORS

How to allow CORS requests

To allow CORS requests, You need to add the following headers to your HTTP response

  • Access-Control-Allow-Origin: * or {specific_host}
  • Access-Control-Allow-Methods: POST, GET, PATCH, DELETE, PUT
  • Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, {your_custom_header_name}

If you request with cookie, you need to add another header Access-Control-Allow-Credentials: true to the HTTP response, and the value of Access-Control-Allow-Origin cannot be *.

Optional HTTP response headers for CORS requests:

  • Access-Control-Max-Age: 86400: tell the browser to cache the preflight response.

Note

  • The wildcard * is not supported for the Access-Control-Allow-Headers value.
  • if the value of Access-Control-Allow-Credentials is true, the value of Access-Control-Allow-Origin cannot be *. The Access-Control-Allow-Credentials: true means request with the cookie.

Preflight requests

A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers. It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header. A preflight request is automatically issued by a browser. If the server allows it, then it will respond to the preflight request with an Access-Control-Allow-Methods response header, which lists DELETE or PUT.

Situations that require a preflight request

  • DELETE and PUT requests.
  • Requests with custom headers.

The preflight response can be optionally cached for the requests created in the same URL using Access-Control-Max-Age header. Note that if it is cached, it will not issue a preflight request.