0

I am trying to read a json file (not on a server, just on a file in a folder on my desktop), using the jQuery method $.get(). Note that the html file and the json file are in the same file directory. For some reason, in the console of the web page, this error occurs:

Access to XMLHttpRequest at 'file:///Users/Harry/Desktop/HTML:CSS:Javascript.html/file.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Here is my code:

<!DOCTYPE html>
<html>
    <body>
        <h1 id="header"></h1>
        <script src="jQuery/jquery-3.4.1.js"></script>
        <script>
            $.getJSON("file.json", function (data) {
                console.log("It worked!");
            });
        </script>
    </body>
</html>

How to stop this error from being thrown?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
MisterHazza
  • 188
  • 1
  • 10
  • Did you check this? https://stackoverflow.com/questions/31269070/cors-error-when-accessing-local-json-file-using-vanilla-js-ajax-request – norbitrial Dec 14 '19 at 17:24
  • 1
    In general, don't use local files directly when doing web programming (unless, of course, you're developing something meant to be used directly from local files). Some browsers (not all) block ajax to local files as you've discovered, and separately there are various other small differences. If doing web development, use a local web server instead. – T.J. Crowder Dec 14 '19 at 17:26
  • Ah ok I see, thanks very much! – MisterHazza Dec 14 '19 at 17:34
  • Is there any way to directly read from a local JSON or text file using javascript/jQuery, without having to use a local web server??? – MisterHazza Dec 14 '19 at 18:20

0 Answers0