I’ve been trying for days on a row now to properly make an API request and insert JSON data into the HTML in pure Javascript using fetch()
in order to build the weather app, without success. I’ve seen a few jQuery solutions around, but I’d like to use this opportunity to learn more about http, headers and promises — hence the extra mile.
I successfully got geolocation to work and logged the API url to the console. However, when the call to fetch()
is added, the following code generates a strange behavior in Codepen and when run natively in Chrome — the browser says the HTML file was not found or deleted. All of it works perfectly on JSFiddle though:
var error = document.getElementById('error');
var location = document.getElementById('location');
var description = document.getElementById('description');
var temperature = document.getElementById('temperature');
function getWeather() {
var fetchData = function(posit) {
var latitude = posit.coords.latitude;
var longitude = posit.coords.longitude;
var url = '* weather api with key *'+latitude+','+longitude;
var request = new Request(url);
fetch(request).then(function(request) {
return request.json();
}).then(function(json) {
location.innerHTML = json.location.region;
description.innerHTML = json.current.text;
temperature.innerHTML = json.current.temp_c;
});
};
var errorMsg = function() {
error.innerHTML = 'Your current browser does not support geolocation.';
};
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(fetchData, errorMsg, options);
};
getWeather();
Can anyone give me a clue of what I’m getting wrong?