Search code examples
reactjsapigithubherokuopenweathermap

Failed openWeatherMap API call


Been working on a small react app that uses the openWeatherMap API to retrieve the current weather conditions for a given location.

The app works flawlessly when tested locally on my system. However, it is failing to return results when deployed to both Github and Heroku.

I've tried practically everything but no way. I even hard-coded the API call to the address bar of my browser and results were returned but when the same search string was hard-coded into the app, the call failed!

Anyone with an idea of what I'm doing wrong here?

Here's is the code block (with hard-coded parameters) where the API call is being made:

fetch(
     "http://api.openweathermap.org/data/2.5/weather?units=metric&q=durban&appid=d6e0e85a41968aaf6240b5ed27522ebd"
   )

Thank you in advance.

N.B: The error being returned is: Failed to fetch

Here is the full fetch function:

  function getForecast(e) {
    e.preventDefault();
    // Next, make the call to the openweathermap API, with the parameters for the specified city
    // fetch(
    //   `http://api.openweathermap.org/data/2.5/weather?units=${unit}&q=${city}&appid=${keys.openweathermap_API_KEY}`
    // )
   
fetch(
     "http://api.openweathermap.org/data/2.5/weather?units=metric&q=durban&appid=d6e0e85a41968aaf6240b5ed27522ebd"
   )

      .then((response) => response.json())
      .then(
        (response) => {
          setResponseObj(response);
        },
        (error) => {
          alert("Error in fetching weather data : " + error.message);
        }
      );
  }

Solution

  • This code seems to work for me as well. You may need to use https for the URL since the browser would reject http requests on a website which has https enabled.