0

its my code:

<script>

function testingAPI(){
theUrl = "https://api.github.com/users/juliolimacostavalladares";
var xmlHttp = new XMLHttpRequest();
xmlHttp.onload = function() {
  alert(xmlHttp.responseText);
};
xmlHttp.onerror = function() {
  alert(xmlHttp.status);
};
xmlHttp.open( "GET", theUrl, false); 
xmlHttp.setRequestHeader("Accept","application/json");
xmlHttp.setRequestHeader("Access-Control-Allow-Origin","*");
xmlHttp.send(null);
}

</script>

<body>
  <button onclick="testingAPI()"> send request </button>
</body>

and when i run it i got CORS error. what can i do to resolve the problem? thank you.

when i try the url in a browser it works. but in javascript it raises a CORS error.

  • 1
    Per https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#cross-origin-resource-sharing, you need to make sure your request includes an appropriate `Origin` header. Consider something like Axios or fetch instead of manually creating XMLHttpRequest objects. – ceejayoz May 01 '23 at 14:04
  • 1
    @ceejayoz There's no need to make sure that the request contains an `Origin` header. Including (or not) such a header is the browser's responsibility, not the client's. You only need to manually include an `Origin` header if you're testing a resource's CORS configuration using some non-browser user agent like `curl`. – jub0bs May 01 '23 at 14:06
  • 1
    @jub0bs You're right; I ran OP's code in CodePen. `xmlHttp.setRequestHeader("Access-Control-Allow-Origin","*");` causes their issue, it seems. Works fine with that line removed. – ceejayoz May 01 '23 at 14:20

0 Answers0