Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error with jquery

I'm currently working on a project using the cloudapp API and I'm using jquery. Here is my code:

 $.ajax({
            headers: { "Accept": "application/json"},
            type: 'GET',
            url: 'http://cl.ly/2wr4',
            crossDomain: true,
            success: function(data, textStatus, request){
                console.log(data);
            }
 });

When I run this I get 200 OK response and this error in Firefox:

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

and this error in Google Chrome:

XMLHttpRequest cannot load http://cl.ly/2wr4. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

and nothing is logged to the console. Please how can I fix this error?

Thanks.

like image 415
mrHorse Avatar asked Sep 18 '14 23:09

mrHorse


People also ask

How do I fix the CORS error?

Short description. Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.

What is CORS error in JavaScript?

CORS is an important security feature that is designed to prevent JavaScript clients from accessing data from other domains without authorization. Modern web browsers implement CORS to block cross-domain JavaScript requests by default.


1 Answers

An important note for those newer coders is that everything on http://enable-cors.org/server.html assumes you have a server running. If you're new, like I was originally, these type of answers don't help.

If you've just made some code on your computer, CodePen, etc - you can't configure this.

There's an important difference between server-side and client-side scripting - your jquery is running on the client side (that is, the users computer / browser) and as such there's no such thing as setting the headers there.

I finally started making progress with this issue when I set up my own server and my own PHP files (PHP is server-side, as such its processed on the server - not the browser) and was able to start making requests just fine.

Adding this for anyone who is being drowned in answers involving the "Header set Access-Control-Allow-Origin "*" answer. It really frustrated me when I started as well.

like image 130
backslash Avatar answered Oct 18 '22 14:10

backslash