CORS and cross-origin HTTP requests

It seems that you have already known quite a few about HTTP request and CORS. But there is always something to learn when you look closer

CORS is short for Cross-Origin Resource Sharing. As the word shows, it gives web servers cross-domain access controls over either static or dynamic data. For static data sharing, its typical type of how CDN works. In essence, it adds new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This is the basic background knowledge.

An interesting note about these requests is there are types of “preflighted” ones. The cause of this is many HTTP methods could have side-effects on server’s data. In order to prevent actual data impact, a more elegant solution would be mandating the browser “preflight” the request to get “approval” from the server first by an HTTP OPTIONS request, then sending the actual request with actual HTTP request.

There are conditions to trigger a CORS preflight, falling any of below 3 conditions will need a preflighted request. Otherwise, a simple request will be sufficient to achieve the goal.

  1. Request uses methods other than following

    • GET
    • POST
    • HEAD
  2. Request includes any below headers
    • Accept
    • Accept-Language
    • Content-Language
    • Content-Type (but note the additional requirements below)
    • DPR
    • Downlink
    • Save-Data
    • Viewport-Width
    • Width
  3. If the Content-Type header has a value other than the following
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

Below is the illustration of how requests are done between client and server.

Here is the full exchange headers info for a preflight request. First is the preflight request.

Second is the actual request for resource.