javascripthttp-status-code-401weather-apijsapi

JavaScript Weather APIKey issue


Code 401

enter image description here

JS Code

enter image description here

My API key is working properly in the browser. But I can't get it in the Live server. It shows 401 error as unauthorized. I turned off my firewall too and also I can't get my results. My console says that same error only.

const apiKey = "5926da84fa5ddbb8fb12992a5d7b7585";
const apiUrl = "https://api.openweathermap.org/data/2.5/weather?units=metric&q=chennai";
async function checkWeather() {
  const response = await fetch(apiUrl + '&appid=${apiKey}');
  var data = await response.json();
  console.log(data);

}

checkWeather();


Solution

  •  const apiKey = "5926da84fa5ddbb8fb12992a5d7b7585";
            const apiUrl = "https://api.openweathermap.org/data/2.5/weather?units=metric&q=chennai";  
    
            async function checkWeather() {
                try {
                    const response = await fetch(`${apiUrl}&appid=${apiKey}`);
                    const data = await response.json();
                    console.log(data);
                } catch (error) {
                    console.error("Error fetching weather data:", error);
                }
            }
    
            document.getElementById("checkWeatherButton").addEventListener("click", checkWeather);
        </script>
     <button id="checkWeatherButton">Check Weather</button>

    you have a single quote but you are using a template literal so you can't use a single quote

    so it should be

    const response = await fetch(`${apiUrl}&appid=${apiKey}`);