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!

1 Like

So I cannot fetch JSON data from other domains?

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

2 Likes

So, should the fix should be done in the front-end?

There’s nothing you can do on the front end, CORS is designed to protect users from malicious front ends imitating a trusted back end. Whatever server you are connecting to uses a CORS header to ensure the data received from that request is only served by the browser on approved domains.

You could try making the GET request on your back end where CORS headers would be ignored, but you might run into issues if whatever server you are querying expects client traffic and instead gets a request from a server. This usually manifests itself as a 403 Forbidden response.

I see. I did get it working by configuring backend to allow cors.
There is a difference between frontend from browser. Since I have no cors issue when using browser, bug I get the issue using my frontend app.Thanks!

FYI ages ago I got it working, there’s a useful package for allowing CORS for express.

Yeah, called CORS.

npm i cors

Then in your server file,

const cors = require('cors');
app.use(cors());