I’m trying to use “worldtimeapi”, but keep getting the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
The same JavaScript works fine when I call “worldclockapi”;
Here is my JavaScript:
…
function pollServer() {
var xmlhttp = new XMLHttpRequest();
var url = “http://worldtimeapi.org/api/ip”;
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("utc").innerHTML = "success";
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
setTimeout(pollServer, 1000);
}
…
Does anyone know how I can get this request working? Any help would be much appreciated
function pollServer() {
var xmlhttp = new XMLHttpRequest();
var url = "https://worldtimeapi.org/api/ip"; // <-- make it a secure call
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('success:', this.responseText)
// document.getElementById("utc").innerHTML = "success";
var myArr = JSON.parse(this.responseText);
console.log(myArr)
// myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
setTimeout(pollServer, 1000);
}
pollServer()
According to the API docs, you don’t need to make the call to an https://
address, however, browsers are frequently requiring it. (Firefox did when I tried to run run it with just http://
.)
And for what it’s worth, you should also check out https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API (Unless there’s an absolute need to use xmlhttp, I wouldn’t. These days I use fetch
or the axios library.)
Thanks for the advice.
My code is working now after I contacted the site owner and they enabled CORS on the server.
1 Like