简体   繁体   中英

didn't get response for XMLHTTPRequest

I try to get weather info from a weather API, everything seems to be working fine but I don't know why I don't get any response, the URL is Working

  //get  Response to weather status based on latitude on longitude positions
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {

            var lat = position.coords.latitude;
            var lon = position.coords.longitude;
            var apiKey = "d64b6f0e97c598ccf0f03718d1690fcc";
            var url = "api.openweathermap.org/data/2.5/weather?lat="
            var URL = url + lat + "&lon=" + lon + "&APPID=" + apiKey;
            console.log(URL);
            var xhr = new XMLHttpRequest();
            xhr.open("GET", URL, true);
            xhr.send();
            xhr.onload = function() {
                if (xhr.status == 200) {
                    document.getElementById("title").innerHTML = this.responseText;
                }
            }
        });

    } else {
        alert("Error");
    }

Open the developer tools in your browser.

Look at the Console. See if there are error messages.

Look at the Network tab. See if the request is being made, if it is being made to where you expect, and if it gets the response you expect.

 var url = "api.openweathermap.org/data/2.5/weather?lat=" 

You forgot the scheme from the URL. You are making the request relative to the URL of the current page. This is almost certainly resulting in a 404 Not Found error.

 xhr.onload = function() { if (xhr.status == 200) { document.getElementById("title").innerHTML = this.responseText; } } 

You have only an onload handler. There is no onerror handler, so no code is triggered then XHR receives the 404 error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM