JQuery GET Requests fail

I have a simple HTML file hosted on glitch which fetches data from another server. Visiting the site normally with chrome returns the data correctly; however I have a JQuery code to fetch that data

$.get("URL", function(data) {})

The request never gets through, i check developer console and see

Access to XMLHttpRequest at ‘http://serverurl/shards/status’ from origin ‘https://myglitch.glitch.me’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

What is the problem? Thanks

The error says it all! Here’s what the Mozilla Docs say about it:

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

An example of a cross-origin request: the front-end JavaScript code served from https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json .

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from, unless the response from other origins includes the right CORS headete

The requests that trigger CORS are:

Hope this helps!

So I cannot fetch JSON data from other domains?

The other server must have the required CORS headers else the request gets rejected.

1 Like