Search code examples
javascriptxmlhttprequestcors

XHR status undefined


I try to send a XHR request to a REST API but I can't get an answer.

Here is my code:

<script>
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "http://www.mocky.io/v2/5a083d8e2f0000c61ee61140", true);
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.onreadystatechange = function() {
    console.log("xhr.readyState: " + xhr.readyState);

    if (xhr.readyState === XMLHttpRequest.DONE) {
      console.log("xhr.status: " + xhr.status);

      if (xhr.status === 200) {
        console.log("xhr.responseText: " + xhr.responseText);

        var response = JSON.parse(xhr.responseText);
      }
    }
  }
  xhr.send();
  console.log("xhr.readyState: " + xhr.readyState);
  console.log("xhr.status: " + xhr.status);
</script>

When I execut it, xhr.status remains undefined and it never enter in the if (xhr.status === 200). I don't know why. Can someone help me?

Edit:

I fixed the JSON but I still have an error:

Google Chrome console showing an error.

The error is about Access-Control-Allow-Origin:

Failed to load http://www.mocky.io/v2/5a083d8e2f0000c61ee61140: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.

So, I read this topic that says I need to add Access-Control-Allow-Origin : * in the HTTP header on mocky.io. I do it but it changes nothing:

enter image description here

Here is the new mocky.io URL:

http://www.mocky.io/v2/5a083d8e2f0000c61ee61140

Does anyone see where my mistake is?


Solution

  • Ok, so it seems that Access-Control-Allow-Origin : * is ignored when we access to the HTML file locally (from file:///C:/.../index.html).

    To make it work, we have to mount a local server (For example, with this Chrome extension) and access to the HTML file through HTTP (http://127.0.0.1:8887/index.html).

    Or use this other Chrome extension that automatically add Access-Control-Allow-Origin : * in the header of the HTTP response.