1

I am trying to load json into a javascript file like so:

$().ready(function () {
      var url = 'url/fname.json';

      $.get(url, function (data) {
        // can use 'data' in here...
        console.log(data)
      });
    });

However, I get the errors "Origin null is not allowed by Access-Control-Allow-Origin" and "[Error] XMLHttpRequest cannot load due to access control checks".

Others have suggested adding Access-Control-Allow-Origin: <origin> | * (Safari 10.1: XMLHttpRequest with query parameters cannot load due to access control checks) or header('Access-Control-Allow-Origin: null'); (XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin), but it's unanswered in those posts where that header goes in an html file.

Is adding this line the solution to my problem? If so, where should I put it?

user2708946
  • 91
  • 3
  • 8
  • That header is for the server side, You can't pass the header in the ajax request. It's not allowed. See [this](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader) in the **note box** – xxMrPHDxx Mar 02 '20 at 03:00
  • `Is adding this line the solution to my problem?` Yes, you may need additional headers as well depending on you specific usage, but at a minium, this one is required. `If so, where should I put it?` That will depend on the technology you're using for your backend, but as a general answer, you'll need to add that header to the "response" that is generated by the server that hosts `url/fname.json`. ie the sever that hosts url/fname.json must also set the `Access-Control-Allow-Origin: *` header stating that anyone can request that file even if the request is from a different sever/domain – Wesley Smith Mar 02 '20 at 03:15
  • If you dont own or have access to the server that hosts `'url/fname.json'` let us know and we can provide alternate solutions – Wesley Smith Mar 02 '20 at 03:17

1 Answers1

2

Seems like you are trying to access cross origin request via ajax. To do that you have to enable CORS in the server side.

You can read more about CORS here. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

fernando
  • 707
  • 8
  • 24