I’m trying to make a request to the Darksky API to show the local weather (a freeCodeCamp project).
To get the response from the server, I’m following the Getting Started with Ajax guide from Mozilla.
As the response of a request from DarkSky is in JSON (if I’m not wrong. click here for more information), I diced to use the first example of the Mozilla’s guide. The basic code from the article is shown below. In this example, the code is ‘GETting’ the information from a local file, ‘test.html’:
<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'test.html');
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.' + httpRequest.status);
}
}
}
}) ();
</script>
Trying to get my response from DarkSky, a just changed the httpRequest.open('GET', 'test.html');
to httpRequest.open('GET', 'https://api.darksky.net/forecast/my_personal_key/0.0000,-111.1111');
. But I got a status code id 0 from my http request.
Making a search, I discovered that there is no code 0 from an http request and that W3C address some possibilities to this code. This answer and that has more information about that.
I’m trying to do that in a local file; using WebStorm IDE (updated); Chrome as a browser; and from Brazil.
Could someone help me get the correct answer from the DarkSky API using the vanilla JavaScript (no jQuery, please).
Thank you for your interest in help me.