When we begins to develop an API, we meet unfortunately a CORS policy violation error when trying to make a cross-origin request
Access to XMLHttpRequest at 'https://datacadamia.com/doc/api/weather_no_cors' from origin 'https://fiddle.jshell.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
and we need to understand what a CORS policy is.
This article tries to explain:
CORS means Cross Origin Resource Sharing (CORS).
The term cross origin refers to a cross origin request that describe:
In this example:
By default and due to the same-origin policy, this is not allowed. And the browser does not allow it by showing you an error message in the console.
To be able to make a cross-origin request demonstration, we will execute a javascript with a fetch from two origin:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
$.ajax({
url: "https://datacadamia.com/doc/api/weather_no_cors",
success: function( result ) {
console.log(result + " degrees" );
}
});
Hover above the console output that should show 23 degrees and click on the Try the code link at the upper right side to load the code on JSFiddle.
Access to XMLHttpRequest at 'https://datacadamia.com/doc/api/weather' from origin 'https://fiddle.jshell.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The CORS policy is a whole protocol (ie procedure/mechanism) that determines when a browser should allow or disallow a cross-origin request.
The configuration is set up via several CORS headers that the HTTP response sends.
Access-Control-Allow-Origin is the most important one and lists the origin of script/page that can access the resource of your web page.
For instance, to allow all web site to query any resources, you need to return in your response, this header with a * value.
Access-Control-Allow-Origin: *
In our case, we have chosen to allow only JsFiddle:
Access-Control-Allow-Origin: https://fiddle.jshell.net
There is various way to set an http response header. You can be set it:
For instance with Apache in a htaccess file
Header set Access-Control-Allow-Origin "https://fiddle.jshell.net"
Each server have different way to configure the response header. See the Enable section of the cors page to get a list of them
We have added this header to the resource https://datacadamia.com/doc/api/weather.
$.ajax({
url: "https://datacadamia.com/doc/api/weather",
success: function( result ) {
console.log(result + " degrees" );
}
});
This getting started gives you an overview of what CORS is and covers the most important configuration header of the CORS policy.
If you want to know more about the whole procedure, see this page What is Cross Origin Resource Sharing (CORS) ?