Home > Net >  JavaScript - API call with fetch doesn't return result
JavaScript - API call with fetch doesn't return result

Time:10-30

I am trying to retrieve weather data from an API by using a JavaScript script on the client side. This is how the code looks like:

  <script>
    async function fetchWeatherData(){
      var url = "http://www.7timer.info/bin/api.pl?lon=-3.57&lat=40.49&product=astro&output=json";
      var weather_data = await fetch(url);
      var weather_json = await weather_data.json();
      return weather_json.dataseries[0].temp2m;
    }
    document.write(await fetchWeatherData());
  </script>

Unfortunately this code doesn't work as I expected. A very similiar Node.JS/Express works great on the server side:

export async function getTemperature(iata){
    let latLong = latLongAirports.find(el => el.iata === iata);
    var url = "http://www.7timer.info/bin/api.pl?lon="   latLong.long   "&lat="   latLong.lat   "&product=astro&output=json"
    const response = await fetch(url);
    const jsonTemperature = await response.json();
    return jsonTemperature.dataseries[0].temp2m;
}

What am I missing or not understanding between the client/server side codes?

CodePudding user response:

the problem ist that you can´t use "top level async" in normal script tags. you need to declare your script tag as type="module". Then it will work like you expect it.

      <script type="module">
        async function fetchWeatherData(){
          var url = "http://www.7timer.info/bin/api.pl?lon=-3.57&lat=40.49&product=astro&output=json";
          var weather_data = await fetch(url);
          var weather_json = await weather_data.json();
          return weather_json.dataseries[0].temp2m;
        }
        document.write(await fetchWeatherData());
      </script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related