I am trying to access a JSON endpoint using Javascript with X-Auth-Token but I’m keeping getting error. It’s JSON for a sports API and I’ve followed every instruction in the documentation and code seems to correct to my knowledge however, I can’t spot the problem.
var main = function() {
var url = "https://api.football-data.org/v4/teams/86/matches?status=SCHEDULED";
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.setRequestHeader("X-Auth-Token", "601a163917fe417da759316ced98462d");
xhr.send(null);
var data = JSON.parse(xhr.responseText);
return data;};
CodePudding user response:
You need to set the request mode to no-cors for it to allow cross-origin resource sharing.
Try doing this.
var myHeaders = new Headers();
myHeaders.append("X-Auth-Token", "your token");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow',
mode: 'no-cors'
};
fetch("https://api.football-data.org/v4/matches?status=FINISHED", requestOptions)
.then(result => console.log(result))
.catch(error => console.log('error', error));
Hope it helps.
CodePudding user response:
you have to wait for a response from the server, XHR has an onl oad method for this
var data = null
var main = function() {
var url = "https://api.football-data.org/v4/teams/86/matches?status=SCHEDULED";
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.setRequestHeader("X-Auth-Token", "601a163917fe417da759316ced98462d");
xhr.onload = () => {
data = JSON.parse(xhr.responseText)
};
xhr.send(null);
}
more here: XMLHttpRequest.onload