No access-control-allow-origin header is present on the requested resource. jquery


In this video I have shown how you can over come the error,

Failed to load : No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access.

This error is because of Cross-Origin Resource Sharing (CORS) issue. This simply means that you are trying access information from other domain which is actually not permitted because of cross domain security issue.

I have shown in the video a real time example how I faced this error and how to overcome.
In the video I have explained 2 ways to over come this,
1 . Use JSONP instead of JSON on requesting data from other domain.

The below program code shows how you can use JSONP to overcome CORS issue,

<html> <head> <script src="jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(e){ e.preventDefault(); var ip_address=$("#ip_address").val(); $.ajax({ type: "GET", url: "http://api.ipinfodb.com/v3/ip-city", data: { key:"9d64fcfdfacc213c7ddf4ef911dfe97b55e4696be3532bf832876c09bad06b", ip:ip_address, format:"json" }, dataType: "jsonp", jsonpCallback: "jsonp_callback", crossDomain: true, success: function(result) { alert(result); }, error: function(result) { alert('error'); } }); }); }); function jsonp_callback(json){ alert(json.cityName); } </script> </head> <body> <center> <h2>Jquery Get Request Test</h2> <form> IP Address : <input type="text" id="ip_address"/><br> <button>Submit</button> </for> </center> </body> </html>

Download the jquery.min.js here jquery.min

2 . Use Javascript instead of Jquery.

The above code functionality can be implemented using only javascript. The use of javascript only can also help to overcome the CORS issue. The javascript code for getting request is,

<!DOCTYPE html> <html> <head> <script> window.onload = function() { document.getElementById("Save").onclick = function fun() { var x = document.forms["myForm"]["ip_address"].value; var Url = "http://api.ipinfodb.com/v3/ip-city/?key=9d64fcfdfacc213c7ddf4ef911dfe97b55e4696be3532bf8302876c09ead06b&format=json&ip=" +x; var xhr = new XMLHttpRequest(); xhr.open('GET', Url, true); xhr.send(); xhr.onreadystatechange = processRequest; function processRequest(e) { if (xhr.readyState == 4 && xhr.status == 200) { // alert(xhr.responseText); var response1 = JSON.parse(xhr.responseText); document.getElementById("statusCode").innerHTML = response1.name + ", " + response1.statusCode; document.getElementById("statusCode").innerHTML = response1.statusCode; document.getElementById("statusMessage").innerHTML = response1.statusMessage; document.getElementById("ipAddress").innerHTML = response1.ipAddress; document.getElementById("countryCode").innerHTML = response1.countryCode; document.getElementById("countryName").innerHTML = response1.countryName; document.getElementById("regionName").innerHTML = response1.regionName; document.getElementById("cityName").innerHTML = response1.cityName; document.getElementById("zipCode").innerHTML = response1.zipCode; document.getElementById("latitude").innerHTML = response1.latitude; document.getElementById("longitude").innerHTML = response1.longitude; document.getElementById("timeZone").innerHTML = response1.timeZone; } } } } </script> </head> <body> <center> Javascript Get Request Test From Form <br> <br> <form name="myForm"> <input type="text" name="ip_address"/> <input type="button" id="Save" onclick="f1()" value="test"/> </form> <center> <br> <br> <table border="1"> <tr><td>statusCode :</td><td id="statusCode"></td></tr> <tr><td>statusMessage :</td><td id="statusMessage"></td></tr> <tr><td>ipAddress :</td><td id="ipAddress"></td></tr> <tr><td>countryCode :</td><td id="countryCode"></td></tr> <tr><td>countryName :</td><td id="countryName"></td></tr> <tr><td>regionName :</td><td id="regionName"></td></tr> <tr><td>cityName :</td><td id="cityName"></td></tr> <tr><td>zipCode :</td><td id="zipCode"></td></tr> <tr><td>latitude :</td><td id="latitude"></td></tr> <tr><td>longitude :</td><td id="longitude"></td></tr> <tr><td>timeZone :</td><td id="timeZone"></td></tr> </table> </body> </html>  

You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml from a file deployed at http://run.jsbin.com due to the same-origin policy.


As the source (aka origin) page and the target URL are at different domains (run.jsbin.com and www.ecb.europa.eu), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET.

In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.



Example:

A page at http://www.example.com/myPage.html can only directly request services that are at http://www.example.com, like http://www.example.com/api/myService. If the service is hosted at another domain (say http://www.ok.com/api/myService), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.

To put it shortly, to perform a (CORS) request* across different domains, your browser:



  • Will include an Origin header in the original request (with the page's domain as value) and perform it as usual; and then

  • Only if the server response to that request contains the adequate headers (Access-Control-Allow-Origin is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).

    • If the expected headers don't come, the browser simply gives up (like it did to you).



* The above depicts the steps in a simple request, such as a regular GET with no fancy headers. If the request is not simple (like a POST with application/json as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS request to the target URL. Like above, it only will continue if the response to this OPTIONS request contains the CORS headers. This OPTIONS call is known as preflight request.

** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers header.



How to fix it?

Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com it will only make regular calls to www.example.com! Other URLs, such as api.example.com or even example.com or www.example.com:8080 are considered different domains by the browser! Yes, if the port is different, then it is a different domain!

Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin) to the server's responses. (Each server/language has a way to do that - check some solutions here.)

Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.


How do you fix no Access

Use addHeader Instead of using setHeader method, response. addHeader("Access-Control-Allow-Origin", "*"); * in above line will allow access to all domains .

How do I fix CORS header Access

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.

How do I add Access

For IIS6.
Open Internet Information Service (IIS) Manager..
Right click the site you want to enable CORS for and go to Properties..
Change to the HTTP Headers tab..
In the Custom HTTP headers section, click Add..
Enter Access-Control-Allow-Origin as the header name..
Enter * as the header value..
Click Ok twice..

What is no Access

This error occurs when a script on your website/web app attempts to make a request to a resource that isn't configured to accept requests coming from code that doesn't come from the same (sub)domain, thus violating the Same-Origin policy.