hannahatl
hannahatl

Reputation: 91

Getting a '400 Bad Request' when I try to link API

I'm starting to make a weather app and I keep getting a '400 bad request' error when I link my API. Any ideas what it could be? I get 'Fetch failed loading: GET' right under it too.

HTML:

<div class = 'header'>
      <h1> Weather Dashboard </h1>
      <input type="text" class="city" placeholder="City Search">
      <!-- Hidden Recent Searches Bar with Bootstrap -->
      <ul class="list-group list-group-horizontal-sm">
      </ul>
      <div class="btnContainer">
          <button class= "goBtn"> Go</button>
      </div>
    </div>

JS:

// Declaring Variables: -----------------------------------------------------------------//
var goBtn =  document.querySelector('.goBtn');
var APIKey = "d04c941f9a17d4fd069f2142973171ec";
var city = document.querySelector('.city');
var searchedCities = [];

function getForecast() {
    var queryUrl = "https://api.openweathermap.org/data/2.5/weather?q=" + city.value + "&appid=" + APIKey;
    fetch(queryUrl)
    .then(function (response) {
      return response.json();
    });

};

goBtn.addEventListener('click', getForecast());

Upvotes: 0

Views: 1030

Answers (1)

You're actually calling the function getForecast() instead of passing a reference to it in your call to addEventListener.

Thus you would need to change

goBtn.addEventListener('click', getForecast());

to

goBtn.addEventListener('click', getForecast);

The '400 bad request' results from a call to the api of openweathermap.com without passing a city as query parameter. I guess this is happening unintended as soon as you load the page. You would also notice this, if you would inspect the response via e.g. browser developer tools.

Upvotes: 1

Related Questions