Error 'Access-Control-Allow-Origin'

0

Hello everyone, how are you? Well I'm doing a course work and at the time of receiving the api data this gives the following error:

  

Failed to load link : Redirect from ' link 'to' link 'has been blocked by CORS policy: No' Access-Control-Allow-Origin 'header is present on the requested resource. Origin 'null' is therefore not allowed access.

I've seen several resolutions about this error, but none have been able to fix it. Anyone who can help me I appreciate !!

follow the javascript:

window.onload = function(){
	var nome = this.queryString("nome");
 	var table =document.getElementById("tab");
 	var element = document.getElementById('element');
 	var power = document.getElementById('power');
	var tbody = document.getElementById("tbo");
	

  var request = new XMLHttpRequest();
  
request.open('GET', 'http://www.superheroapi.com/api/2195914800646269/search/' + nome , true);
request.onload = function () {
// Vary= Origin;


  var data = JSON.parse(this.response);
  if (request.status >= 200 && request.status < 400) {
  	
   tbody.innerHTML="";
    
  	element.innerHTML +="<h2>resultados para " +nome+"</h2>";
  	power.innerHTML +="Resultados para " +nome;

	

  try {
        for(var i=0; i<=data.results.length; i++){
          tbody.innerHTML += "<tr><td> <center><img src=" +data.results[i].image.url + " class='imgherois'></center>" +
           "<tr><td>"+"Nome: " +data.results[i].name +    
           "<tr><td>"+ "Nome Real: " +data.results[i].biography["full-name"] +   
           "<tr><td>"+ "Alter-Ego: " +data.results[i].biography["alter-egos"] +   
           "<tr><td>"+ "Aliados: " +data.results[i].biography.aliases +   
           "<tr><td>"+ "Naturalidade: " +data.results[i].biography["place-of-birth"] +   
           "<tr><td>"+ "Apareceu pela primeira vez em: " +data.results[i].biography["first-appearance"] +   
           "<tr><td>"+ "Universo: " +data.results[i].biography.publisher +   
           "<tr><td>"+"Do Bem ou do Mau: " +data.results[i].biography.alignment+    
           "<tr><td>"+"Inteligencia: " + "<div class='porcentagem porc'><div class='por cor porc' + style=width:"+data.results[i].powerstats.intelligence+"%>"+data.results[i].powerstats.intelligence+"</div></div>"+ 
           "<tr><td>"+"Força: "+ "<div class='porcentagem porc'><div class='por cor porc' + style=width:"+data.results[i].powerstats.strength+"%>"+data.results[i].powerstats.strength+"</div></div>"+ 
           "<tr><td>"+"Velocidade: "+ "<div class='porcentagem porc'><div class='por cor porc' + style=width:"+data.results[i].powerstats.speed+"%>"+data.results[i].powerstats.speed+"</div></div>"+ 
           "<tr><td>"+"Durabilidade: "+ "<div class='porcentagem porc'><div class='por cor porc' + style=width:"+data.results[i].powerstats.durability+"%>"+data.results[i].powerstats.durability+"</div></div>"+ 
           "<tr><td>"+"Poder: "+ "<div class='porcentagem porc'><div class='por cor porc' + style=width:"+data.results[i].powerstats.power+"%>"+data.results[i].powerstats.power+"</div></div>"+ 
           "<tr><td>"+"Combate: "+ "<div class='porcentagem porc'><div class='por cor porc' + style=width:"+data.results[i].powerstats.combat+"%>"+data.results[i].powerstats.combat+"</div></div>"+   
           "<tr><td>"+"Genero: " +data.results[i].appearance.gender+    
           "<tr><td>"+"Raça: " +data.results[i].appearance.race+    
           "<tr><td>"+"Altura: " +data.results[i].appearance.height+    
           "<tr><td>"+"Peso: " +data.results[i].appearance.weight+    
           "<tr><td>"+"Cor dos Olhos: " +data.results[i].appearance["eye-color"]+    
           "<tr><td>"+"Cor dos Cabelos: " +data.results[i].appearance["hair-color"]+    
           "<tr><td>"+"Oucupação: " +data.results[i].work.occupation+    
           "<tr><td>"+"Base: " +data.results[i].work.base+    
           "<tr><td>"+"Afiliação: " +data.results[i].connections["group-affiliation"]+    
           "<tr><td>"+"Parentes: " +data.results[i].connections.relatives+"</td></tr>";    

	     } 
  } catch (e) {
     //console.log(e);
     if (data.results == null) {
     	tbody.innerHTML += "<tr><td>"+"O Herói ou Vilão não foi encontrado!!! =("+"</td><td>";
     }
    return undefined;
  }


  } else {
    console.log('error');
  }

}
  request.send();

}

// função pra ler querystring
function queryString(parameter) {  
              var loc = location.search.substring(1, location.search.length);   
              var param_value = false;   
              var params = loc.split("&");   
              for (i=0; i<params.length;i++) {   
                  param_name = params[i].substring(0,params[i].indexOf('='));   
                  if (param_name == parameter) {                                          
                      param_value = params[i].substring(params[i].indexOf('=')+1)   
                  }   
              }   
              if (param_value) {   
                  return param_value;   
              }   
              else {   
                  return undefined;   
              }   
        }
    
asked by anonymous 08.11.2018 / 00:49

3 answers

0

Welcome to Stack Overflow in Portuguese, Matheus. Take a look at the help center if you have any questions about the site.

In this line:

request.open('GET', 'http://www.superheroapi.com/api/2195914800646269/search/' + nome , true);

Try switching to:

request.open('GET', 'http://www.superheroapi.com/api.php/2195914800646269/search/' + nome , true);

Apparently there is a problem with the redirect that the API is doing by sending status 302, and in that redirect something (I can not tell you exactly what it is) with the CORS policy.

But it works, as can be seen here: link

    
08.11.2018 / 12:50
0

A definition of what is happening

Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction is called a policy of the same origin. The same source policy prevents a malicious site from reading sensitive data from another site. Sometimes, you may want to allow other sites to make requests between sources in your application.

Among the source resource sharing (CORS) is a W3C standard that allows a server to relax the same source policy. Using CORS, a server can explicitly allow some requests between sources while rejecting others.

source: link

Your problem is probably in Api and the request is being made, so you can take a look at how to enable CORS in your api so that it can allow requests.

    
08.11.2018 / 13:07
0

I believe the problem is not "Access-Control-Allow-Origin", I did an example here and did not show me this error, in fact this api does not have access to external query

var xhr = new XMLHttpRequest();
var nome = "";
xhr.open("GET","http://www.superheroapi.com/api.php/2195914800646269/search/" + nome , true);
xhr.send(null);

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