KAT KAT - 3 months ago 22
jQuery Question

$.getJSON adds ' http://localhost:3000' to api URL

error


I am building Weather-App, and when I call API,

$.getJSON
adds my localhost addres.


GET
http://localhost:3000/api.openweathermap.org/data/2.5/weather?lat=50.064650099999994&lon=19.9449799&APPID=f7dcb8e5d6a1f2126a2080a1e0d17b5a
404 (Not Found)


$("#getLocation").on("click", function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$("#location").html("latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude);
lat = position.coords.latitude;
lon = position.coords.longitude;

api = "api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=f7dcb8e5d6a1f2126a2080a1e0d17b5a";

console.log(api);

$.getJSON(api, function(json) {
$("#api").html(json);
});
});
}

});

Answer

Since the URL doesn't contain //servername, it's interpreted as a relative URL from the current page's path. Use:

        api = "//api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=f7dcb8e5d6a1f2126a2080a1e0d17b5a";