XMLHttpRequest cannot load URL


#1

So, I have this function to fetch the Twitch API

function getFcc() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "https://wind-bow.gomix.me/twitch-api/users/freecodecamp", false);
  xhr.setRequestHeader( 'Access-Control-Allow-Origin', '*' );
  xhr.setRequestHeader( 'Access-Control-Allow-Methods', 'GET' );
  xhr.setRequestHeader( 'Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token' );
  xhr.send();
  let img = JSON.parse(xhr.responseText).logo;
  
  xhr.open("GET", "https://wind-bow.gomix.me/twitch-api/streams/freecodecamp", false);
  xhr.setRequestHeader( 'Access-Control-Allow-Origin', '*' );
  xhr.setRequestHeader( 'Access-Control-Allow-Methods', 'GET' );
  xhr.setRequestHeader( 'Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token' );
  xhr.send();
  let res = JSON.parse(xhr.responseText);
  if (res.stream === null) {
    return {'img': img, 'status': 'OFFLINE'};
  } else {
    return {'img': img, 'status': res.stream.channel.status};
  }
}

But, on the console it says “Failed to load resource: the server responded with a status of 404 ()”, “XMLHttpRequest cannot load https://wind-bow.gomix.me/twitch-api/users/freecodecamp. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://s.codepen.io’ is therefore not allowed access. The response had HTTP status code 404.”,
“Uncaught DOMException: Failed to execute ‘send’ on ‘XMLHttpRequest’: Failed to load 'https://wind-bow.gomix.me/twitch-api/users/freecodecamp’.
_ at getFcc (https://s.codepen.io/edwinharly/debug/EXqYJO/XxrVwDppExbA:80:7)_
_ at HTMLDocument. (https://s.codepen.io/edwinharly/debug/EXqYJO/XxrVwDppExbA:59:16)_”

I’ve tried some solutions from StackOverlow, which is adding those 3 request header, but still it doesn’t work.


#2

is there a reason that you have chose not to use fetch. im not an expert by any stretch but ive found fetch to work pretty good for stuff like this. the whole cors thing i can’t really wrap my head around yet


#3

Ok, I used XMLHttpRequest on both Local Weather and Wikipedia project and it works fine, so I’ll try to use fetch on this one, thx.