Bahador Saket
Bahador Saket

Reputation: 1035

XMLHttpRequest 'Access-Control-Allow-Origin' Error

I am writing a web-based application where I need to access the txt file that is hosted online and read the file. I am using following code to do it:

var oReq = new XMLHttpRequest();
  oReq.addEventListener("load", function(){
     // parse the file
  }
})
oReq.open("GET","https://bahadorsaket.com/others/ranking.txt");
oReq.send();

I got this error:

Failed to load https://bahadorsaket.com/others/ranking.txt: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

After searching and reading this post, I tried changing my code to this.

var oReq = new XMLHttpRequest();
  oReq.addEventListener("load", function(){
     // parse the file
  }
})
oReq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
oReq.open("GET","https://bahadorsaket.com/others/ranking.txt");
oReq.send();

This time I got this error:

Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.

Any idea how to fix this problem? I am very new to these kinds of stuff!!!

Upvotes: 0

Views: 9633

Answers (2)

Sina
Sina

Reputation: 369

For the specific error:

Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.

It's because you're setting the header before invoking the open method on the XMLHttpRequest object. Reordering to this will fix that specific error:

var oReq = new XMLHttpRequest();
  oReq.addEventListener("load", function(){
     // parse the file
  }
})
oReq.open("GET","https://bahadorsaket.com/others/ranking.txt");
oReq.setRequestHeader( 'Access-Control-Allow-Origin', '*');
oReq.send();

But like the others have mentioned, you may then face other issues if the backend server isn't configured to support CORS.

Upvotes: 1

BrettC
BrettC

Reputation: 71

Although not the best method, you can use a proxy also.

$.ajaxPrefilter( function (options) {
  if (options.crossDomain && jQuery.support.cors) {
    var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
    options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
    //options.url = "http://cors.corsproxy.io/url=" + options.url;
  }
});

$.get(
    'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
    function (response) {
        console.log("> ", response);
        $("#viewer").html(response);
});

I used this in the past and it worked very well.

Taken from this post.

Upvotes: 1

Related Questions