How to overtake XMLHttpRequest can not load?

3

This error appears to me. How to overcome it?

  

XMLHttpRequest can not load "url example". In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Code

var url = "http://www. url exemplo"; //url que tem a informação
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var json = JSON.parse(xmlhttp.responseText);
        console.log(json);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send(); 
    
asked by anonymous 14.04.2015 / 11:48

2 answers

3

First, note that browser set the call source to null . The source (the trio schema / domain / port that identifies where you are) usually refers to the site the code is running on - either the site itself (if the code is yours) or not if it's a third-party code - an ad for example - running on your site). But if it is null, this is a sign that the code is in a "sandboxed" environment. Most likely, a iframe with the attribute sandboxed and without the allow-same-origin option.

A code under these circumstances is not considered reliable by your host , and thus can not access resources from the same source (ie # with including making ajax calls to the same source . I think some browsers would not even allow ajax calls anywhere (some tests I've done in the past - see link above - have had this result).

However, it seems to me that the browser you're using is more "reasonable" - it allows sandboxed content to do ajax for servers that implement Cross-Origin Resource Sharing (CORS). In this way, he checked that the server in question (its own? Some other?) Returned the header Access-Control-Allow-Origin , to find out if other sites were allowed to make ajax requests for it. In the absence of a positive response (i.e. the absence of header ), he took the secure option of blocking the call.

To solve, you would have to of the three one:

  • Remove the sandboxed attribute from your iframe ;
  • add the allow-same-origin option to it; or:
  • Enable CORS on your server.

Each of these has security implications. You must first answer to yourself "where does this code come from?", "Is it reliable?" and "what would it be bad if any X site made ajax requests for my server?" before deciding on a suitable solution.

    
14.04.2015 / 12:08
0

Hello. you can do so: Example:

var xhr = new XMLHttpRequest();

xhr.open("GET","https://api.github.com/users/itasouza");
xhr.send(null);

xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){
        console.log(JSON.parse(xhr.responseText));
    }
}
    
08.11.2018 / 14:06