I am trying to build a weather app and anytime I try to search for a city it shows undefined and humidity and windspeed values do not change. Also I get Cod:401 invalid API key error.
I have tried many ways to see what actually went wrong. But still can't find the answer.
<script>
const apiKey = "c783c8739883eb8cfbb8e5fb0a959dc5";
const apiUrl =
"https://api.openweathermap.org/data/2.5/weather?units=metric&q=";
const searchBox = document.querySelector(".search input");
const searchBtn = document.querySelector(".search button");
async function checkweather(city) {
const response = await fetch(apiUrl + city + `&appid=$(apikey)`);
var data = await response.json();
console.log(data);
document.querySelector(".city").innerHTML = data.name;
document.querySelector(".temp").innerHTML =
Math.round(data.main.temp) + "°c";
document.querySelector(".humidity").innerHTML =
data.main.humidity + "%";
document.querySelector(".windspeed").innerHTML =
data.wind.speed + "km/h";
}
searchBtn.addEventListener("click", () => {
checkweather(searchBox.value);
});
</script>
Correct your template literal syntax
TL;DR.. You have
$(apikey)in yourfetchmethod with parentheses (()). Change them to${apikey}with curly braces ({}).Javascript template literal syntax goes.
You have used parentheses instead of curly braces, which is syntactically incorrect. Try fixing it first.