Cod: 401 'message' invalid API key using open weather API

89 views Asked by At

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>
1

There are 1 answers

0
Bumhan Yu On

Correct your template literal syntax

TL;DR.. You have $(apikey) in your fetch method with parentheses (( ) ). Change them to ${apikey} with curly braces ({ } ).

Javascript template literal syntax goes.

`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tagFunction`string text ${expression} string text`

You have used parentheses instead of curly braces, which is syntactically incorrect. Try fixing it first.