top of page

CORS Explained

You can read more about HTTP here.

CORS - Cross Origin Resource Sharing.

Let's understand the difference between Origin and Site.

Let's take an URL:

http://app.paperless.com/about

Here

http:// --> Scheme(protocol used)

app --> Sub-domain

paperless -> second-level domain

com --> Top-level domain

about --> sub-directory


Take a long URL like this below. (includes the port number and query string)

What is Origin?

Origin is a combination of scheme, domain, and port.


What is a Site?

The site combines the Top-level Domain and part of the Domain just before it.

In the example,

Consider this,

https://app.paperless.com:443

Here the Top-level Domain is 'com.'Here the site will be part of Domain just before TLD.

Fun fact: WWW is also a subdomain like 'app' and 'hello' above.

Therefore

  • http://example.com

  • http://www.example.com

  • http://myapp.example.com

are of different origins.


HTTP Headers related to CORS:

Request:

origin:http://example.com --> automatically set by the browser

Response:

Access-Control-Allow-Origin: * --> accepts all origins

Access-Control-Allow-Origin: https://app.paperless.com --> allows only this site

It is essential to understand preflight requests. Preflight requests check whether the requested HTTP method is allowed on the server or not.

HTTP method used in the preflight request is Options

Specific requests don't trigger preflight requests; these are called simple requests.

As a rule of thumb, any requests that don't cause side-effect on server data are called 'Simple requests.'


CORS Preflight:

OPTIONS /doc HTTP/1.1
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type

This will tell that I am going to send a request with the method 'Post'.If the request is sent, it may have some custom headers. Access-Control-Request-Headers give this custom header instruction: X-PINGOTHER, Content-Type. Prefix X will tell it is the custom header.


The response from the server would be

Access-Control-Allow-Origin: https://app.paperless.com
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400 --> In seconds (24 hours) --> How long the preflight request can be cached

bottom of page