Weather Widget Error

Hi all

I’m trying to get the following code to work and return some weather information in the console, for some reason though I keep getting the following error in the console

GET http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units} 401 (Unauthorized)
searchWeather @ index.js:9
(anonymous) @ index.js:23
index.js:17 {cod: 401, message: "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}

My Code is as follows

HTML

<div id="searchContainer">
  <input class="searchControl" type="text" placeholder="City Name" id="searchInput">
  <button class="searchControl" id="searchBtn">Search</button>
</div>  

<div id="weatherContainer">
    <div id="weatherDescription">
        <h1 id="cityHeader"></h1>
        <div id="weatherMain">
            <div id="temperature"></div>
            <div id="weatherDescription"></div>
            <div><img id="documentIconImg"></div>
        </div>
        <hr>
        <div id="windSpeed" class="bottomDetails"></div>
        <div id="humidity" class="bottomDetails"></div>
    </div>
</div>

JavaScript

let appId = '69eb806ae1f5d9152bad587b04da1929';
let units = 'imperial';
let searchMethod; 'zip';

function searchWeather(searchTerm) {
  fetch('http://api.openweathermap.org/data/2.5/weather?${searchMethod}=${searchTerm}&APPID=${appId}&units=${units}').then(result => {
    return result.json();
  }).then(result => {
    init(result);
  })
}

function init(resultFromServer) {
  console.log(resultFromServer);
}

document.getElementById('searchBtn').addEventListener('click', () => {
  let searchTerm = document.getElementById('searchInput').value;
  if (searchTerm)
    searchWeather(searchTerm);
})

Is the error to do with the code? because as far as I’m aware, I’m making use of the free service that openweathermap provides. The tutorial I’m following works fine but I can’t seem to get it to working when I do it.

Thanks all!

Is that appId the one you received when you signed up for an account?

Yes it is, I even generated another one to see if I could get that working but I’m having the same issue.

After reviewing your code again, I discovered three issues.

  1. let searchMethod; ‘zip’; Your should be assigning a value here.

  2. You have wrapped your fetch url in single quotes. However, since you are trying to use a template literal here, it should be surrounded by single back ticks.

  3. You can not request a non-secure (http) url from a secure one (Codepen uses https). It turns out openweathermap.org offers an https version, so just change the http to https.