Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAMPP: JQuery Ajax - Access-Control-Origin error

I am trying to use JQuery ajax in order to retrieve data from a source on a different domain.

I am getting a No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

E.g. I would like to retrieve the whole DOM of e.g. stack overflow main page.

    $(document).ready(function() {
      $.ajax({
        url: "http://stackoverflow.com/",
        success: function(data) {
          console.log(data);
          $("h1").text("Success => check console");
        },
        error: function(data) {
          console.log(data);
          $("h1").text("Error => check console");
        }
      });
    });
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
  <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta charset='utf-8'>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test</title>
  <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
</head>

<body>
  <h1></h1>
</body>

</html>

What I tried:

  • I was running this on my Apache server (XAMPP). Found out I need to set .htaccess needs to Header add Access-Control-Allow-Origin "*" (for security reasons the Kleene star should be replaced with the required URI). I was playing a lot with different .htaccess
  • So now I am trying to retrieve it without a server on the backend, purely with the code I provided in the snippet (running it from file:///C:/)

EDIT

Solved the problem (also accepted my answer unless someone more skillful comes up with a better explanation) and understand the situation from a practical point of view.

Footnote: This example is just to illustrate the problem. In the final solution, I just want to use the AJAX to send REST requests to another PC in our VLAN where a server is running.

like image 983
Igor L. Avatar asked Apr 21 '16 08:04

Igor L.


People also ask

How do I fix a CORS issue in Ajax?

Solution. To resolve this error, update your code to make the AJAX call to the new URL provided by the redirect. For more information, see the MDN article CORS request external redirect not allowed.

How do you fix cross origin request blocked the same origin policy disallows reading the remote resource at?

“Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.example.com/resource. This can be fixed by moving the resource to the same domain or enabling CORS.”

What is Crossdomain in Ajax?

CORS is a mechanism that defines a procedure in which the browser and the web server interact to determine whether to allow a web page to access a resource from different origin. Figure 2. Cross domain ajax request. When you do a cross-origin request, the browser sends Origin header with the current domain value.


2 Answers

TL;DR:

  • If I host an API I need to allow cross-origin requests.
  • If I want to access an API, the server hosting the API needs to allow cross-origin requests.
  • The code was not a problem, nor was me running it from file://, the snippet works fine

Longer explanation in laymans terms:

  • When hosting a server were you want to host an API, you need to allow Access Control Allow Origin headers on the server. You can specify which servers are allowed to access the API.

    If I am running an APACHE server and I want to serve some data on REST requests, I need to specify clients that are allowed to access the services I provide. This is done in .htaccess by adding:

    Header add Access-Control-Allow-Origin *

    To be more secure, its possible to just allow specific origins:

    Header set Access-Control-Allow-Origin http://www.specific_origin.com

  • On the other hand, if another server hosts API on their domain, the admin of the server needs to allow the origins they accept requests from (this was my case). For example, the server containing the API was written in python, so the code is the following:

    self.set_header('Access-Control-Allow-Origin', '*')

  • Once this was set, even a request from a script in the provided snippet works well just from accessing a "file" address e.g. file:///C:/tasks/crawler/index.html

like image 83
Igor L. Avatar answered Oct 15 '22 23:10

Igor L.


For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts.

This is called CORS (Cross Origin Resource Sharing). There are restrictions while making ajax request to the server other than the document's domain.

One can make a cross origin request if the request is suitable for either:

  1. the request is a simple request
  2. The other domain permits the client to access its recources.

Why your GET request is not a simple request?

In your case, if you would like to retrieve the whole DOM, the content type of the response of the GET request will be 'text/html'. And the request will not be a "simple request" any more.

So the other domain (that you want to access) has to permit for your requests:

  • Permission for the document origin. (null for your case)
  • Permission for the request method.

Your error message is clear enough that "Access-Control-Allow-Origin" header is not supplied by other server.

How do you solve your problem?

By adding your API servers "Access-Control-Allow-Origin" header. Have a look on this site: http://enable-cors.org/server.html

Resources:

  • https://www.w3.org/TR/cors/
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
like image 44
ykaragol Avatar answered Oct 15 '22 23:10

ykaragol