CodeSchlocker
CodeSchlocker

Reputation: 61

How do I get around Cross Origin Requests being blocked?

I'm trying to retrieve a file, on the server that I run my php on. A web hosting service.

I've encountered this problem before, trying to access a file from html either locally, or from a server. My code is:

<! DOCTYPE html >

<html>
   <head>
       <title>retrieve_activities_json.html</title>
   </head>
   <body>
   
       <p id="demo"></p>
       
       <script>
       var xmlhttp = new XMLHttpRequest();
       xmlhttp.onreadystatechange = function() {
           if( this.readystate == 4 && this.status == 200 ) {
               var activities_obj = JSON.parse(this.responseText);
               document.getElementById('demo').innerHTML = activities_obj[0];
           }
   
       };
   
       xmlhttp.open("GET","activities.json", true);
       xmlhttp.send();
       
       </script>
   </body>

</html>

Is there any settings to my browser, or to the webhosting server that will help me defeat this error message:

Access to XMLHttpRequest at 'file:///D:/Web%20Development%20Tutorials/JavaScript%20Practice/activities.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

Upvotes: 3

Views: 29624

Answers (1)

kn0wmad1c
kn0wmad1c

Reputation: 110

Seeing Origin 'null' means that you're trying to dynamically load files from your local machine. This is not allowed by the Same-Origin Polciy (CORS) that Chrome is telling you about. Chrome is particularly strict on this rule.

While there are ways to get around it, I really wouldn't recommend it.

Your best bet would be to set up a free, local web server and run your test code from there.

Upvotes: 4

Related Questions