Cross Origin Resource Sharing (CORS)

CORS (Cross-Origin Resource Sharing) is a mechanism by which data or any other resource of a site could be shared intentionally to a third party website when there is a need. Generally, access to resources that are residing in a third party site is restricted by the browser clients for security purposes.

Client side code to make an HTTP Call would look like below,

function httpGetAction(urlLink)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", urlLink, false ); 
    xmlHttp.send();
    return xmlHttp.responseText;
}

This native JavaScript method is intended to make an HTTP call to the given link urlLink via the GET method and return the response text from the third party resource.

By default, a request to non-parent domains (domains other than the domain from which you are making the call) is blocked by the browser. If you try to do so, the console would throw the following error.,

Failed to load https://contribute.geeksforgeeks.org/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://www.google.com' is therefore not allowed access.

Of course, there are some cases where you need to access a third party website like getting a public image, making a non-state changing API Call or accessing other domain which you own yourself. There are some ways to achieve this, as and when necessary.

One could get an idea from the error message that the Access-Control-Allow-Origin Header is not present on the requested resource. It simply means that the target website whose resource you are trying to access haven’t specifically allowed you to get the resource from their site.

This could be done with an additional HTTP Header, Access-Control-Allow-Origin. This header could take the following values.,