CORS – Cross Origin Resource Sharing

The browser has a CORS mechanism which  restricts the loading of resources from another domain. CORS defines a way in which a browser and server can interact to determine whether it is safe to allow the cross-origin request

The header which controls accesses is
Access-Control-Allow-Origin

So if this header is not present, the CORS request fails. Even if it is present, it should be having the value which allows the requesting domain in it.

To allow all domains one can use “*”.

However, one web page can freely embed images, videos, stylesheets etc. But AJAX requests to another domain aren’t allowed as per this rule.

Preflight Request

Most modern browsers make an extra request prior to executing the requested AJAX request to the other server asking them if such a request is allowed. 

The requested server needs to be respond with two headers
If service.example.com is willing to accept the action, it may respond with the following headers:

Access-Control-Allow-Origin: http://www.example.com

Access-Control-Allow-Methods: PUT, DELETE

If the origin and method both are allowed as mentioned in the request, it then goes ahead and makes the request else leaves it.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *