When I send a CORS request to the TVDB API I always get an error: “has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”
function sendForAPIToken() {
var apiKey = getAPIKey();
var url = 'https://api.thetvdb.com/login';
var xhr = createCORSRequest("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.send(JSON.stringify({
apikey: apiKey
}));
xhr.onreadystatechange = function () {
if (xhr.readyState >= 4 && xhr.status == 200) {
alert(JSON.parse(xhr.responseText).token);
return JSON.parse(xhr.responseText).token;
}
}
}
/* function sendGetAPIToken() {
$.ajax({
type: 'POST',
url: "https://api.thetvdb.com/login",
processData: true,
data: JSON.stringify({apikey: getAPIKey()}),
dataType: "application/json",
success: function (data) {
retrieveAPIToken(data);
}
});
} */
function retrieveAPIToken(data) {
var processedData = JSON.parse(data);
alert(processedData.token);
return processedData.token;
}
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
I expect to get a token with my apiKey from TheTVDB but instead, I get “has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”