'Access-Control-Allow-Origin' error

Asked

Viewed 1,771 times

0

Hello everyone all right? Well I’m doing a course work and in time to receive the data from the api this giving the following error:

Failed to load http://www.superheroapi.com/api/2195914800646269/search/batman: Redirect from 'http://www.superheroapi.com/api/2195914800646269/search/batman' to 'https://www.superheroapi.com/api.php/2195914800646269/search/batman' 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 have seen several resolutions about this error, but none of them have been able to correct it. Who can help me I thank!!

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;   
              }   
        }

  • try using a browser extension https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-ntp-icon

  • In my view, this problem is in relation to the API service you are using, basically saying that you are not allowed to use this service. It has nothing to do with your javascript, but with the backend of this service 'superheroapi'

3 answers

0


Welcome to Stack Overflow in English, Matheus. Take a look at 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 sending the status 302, and in this redirect something (I can’t tell you exactly what it is) with the CORS policy.

But it works, as can be seen here: https://jsfiddle.net/adrianprado/jw5bgred/9/

0

A definition of what is happening

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

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

source:https://docs.microsoft.com/pt-br/aspnet/core/security/cors?view=aspnetcore-2.1

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

0

I believe the problem is not "Access-Control-Allow-Origin," made an example here and do not show me this error, actually 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));
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.