Javascript – How to solve Cross-Origin Request Blocked error in firefox

htmljavascriptjquery

<script>
    $.getJSON('url', function (data) {
        console.log("Before:"+data);
        t = data;
        console.log("After:"+t);
    });
</script>

When I am using getJson method to get data from REST API , I am getting the error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at the url. This can be fixed by moving the resource to the same domain or enabling CORS.

How do I solve this? Please help.

Best Solution

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at the url. This can be fixed by moving the resource to the same domain or enabling CORS.

It means you should have api (url in your code) and the file which has your script must be in same domain

Or

Add the Access-Control-Allow-Origin header in the API(url in your code) domain

<FilesMatch "\.(php)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

* to allow all cross domainrequests