"Encountering an error retrieving weather forecast API in JavaScript - issue with

I've been attempting to fetch the weather forecast API JSON in a similar manner to how I accessed the current weather API, but unfortunately, it doesn't seem to be working no matter what approach I take.

    let inOneDay = {
fetchWeather: function(){
    fetch("https://api.openweathermap.org/data/2.5/forecast?q=Dortmund&units=metric&cnt=1&appid=758fce6dd3722cf25cd213a13bbc5484"
    ).then(resp => resp.json())
    .then(data => console.log(data));
}

};

I'm puzzled as to where I may have made an error. The logic I used to successfully implement the code below should theoretically apply:

let weather = {
    fetchWeather: function(){
        fetch("https://api.openweathermap.org/data/2.5/weather?q=Dortmund&units=metric&appid=758fce6dd3722cf25cd213a13bbc5484"
        ).then((response) => response.json())
        .then((data) => this.displayWeather(data));
    },
    displayWeather: function(data){
        const{icon,description} = data.weather[0];
        const{temp} = data.main;
        document.querySelector(".icon").src = "https://www.openweathermap.org/img/wn/" + icon + ".png";
        document.querySelector(".celsius").innerText = Math.round(temp) + "°C";
        document.querySelector(".desc").innerText = description;
    }

}

Any thoughts or suggestions would be greatly appreciated!

Answer №1

Upon analyzing the json response received from the API, it appears that the OP code expects certain fields that are not provided by the service.

const result = 
{"cod":"200","message":0,"cnt":1,"list":[{"dt":1631577600,"main":{"temp":13.31,"feels_like":13.05,"temp_min":13.31,"temp_max":15.87,"pressure":1018,"sea_level":1018,"grnd_level":1007,"humidity":90,"temp_kf":-2.56},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"clouds":{"all":95},"wind":{"speed":1.42,"deg":94,"gust":2.29},"visibility":10000,"pop":0,"sys":{"pod":"n"},"dt_txt":"2021-09-14 00:00:00"}],"city":{"id":2935517,"name":"Dortmund","coord":{"lat":51.5167,"lon":7.45},"country":"DE","population":588462,"timezone":7200,"sunrise":1631595820,"sunset":1631641686}};

const result0 = result.list[0];        // note .list[0]
const weather0 = result0.weather[0];   // note weather[0]
const main = result0.main;             // note that main is a sibling property to weather
const temp = main.temp

console.log(`weather data: ${JSON.stringify(weather0)}`);
console.log(`main data: ${JSON.stringify(main)}`);
console.log(`temperature: ${temp}`);

Ensure to verify for any errors prior to referencing the result. It also seems like the api includes a cnt property which could indicate the number of elements in the list.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize PHP to open a JSON string file and then convert it into an array

<?php $postcode=$_POST['script']; $myfile = '{ "1": { "Brand":"MITSUBISHI HEAVY INDUSTRIES, LTD.", "Model_No":"SRK20ZMXA-S / SRC20ZMXA-S", "C.Power_Inp_Rated":0.35, "H.Power_Inp_Rated":0.45, "KWH":1881.95, "Cost":564.585}, "2": { "Br ...

Exploring Ember Octane (version 3.22 and above): benefits of using {{on 'click' this.function}} over traditional onclick={{this.function}} method

When working with Ember Octane, there are two different ways to attach a function to an event in an hbs file. The first way is the EmberJS approach: {{on 'click' this.function}} Alternatively, you can use the classic HTML method: onclick={{this ...

Attempting to run driver.execute_script(gooogletag but no response was received

I have been attempting to receive responses in the console from the browser when running googletag parameters with Selenium, but unfortunately I have not been successful. Even after trying .execute_async_script('googletag.pubads()') and putting ...

What is the method for assigning classes to a Vue.js Functional Component from its parent component?

Imagine a scenario where I have a functional component: <template functional> <div>Some functional component</div> </template> Now, when I render this component within a parent element with classes: <parent> <som ...

Retrieve a single value from a JavaScript array

There must be something simple I am missing here, as all the search results I found relate to looping over arrays, which is not what I want. My ajax call returns a response in the form of a straightforward array. When I use console.log(response); in the s ...

Navigating in Angular with parameters without modifying the URL address

In a nutshell, my goal is to navigate to a page with parameters without showing them in the URL. I have two components: Component A and B. What I want to do is route to B while still needing some parameters from A. I know I can achieve this by setting a ...

Ensuring consistency of Angular route data and maintaining data synchronization

In my Angular application, I have a table that displays a set of items and allows inline editing directly within the table. The data is fetched from an HTTP API through a service, which retrieves the data and injects it into the application. The issue ari ...

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

Tips for adding content to a textarea with JavaScript without disrupting the editing history

I have a specific requirement where I want the user to be able to highlight text in a textarea, then press ctrl + b to automatically surround that selected text with stars. Here is what I envision happening: 1) The initial content of the textarea is: "he ...

Typescript - unexpected behavior when using imported JavaScript types:

I am struggling with headaches trying to integrate an automatically generated JavaScript library into TypeScript... I have packaged the JavaScript library and d.ts file into an npm package, installed the npm package, and the typings modules in the TypeScr ...

Is there a way to send all the results of a Flask database query to a template in a way that jQuery can also access

I am currently exploring how to retrieve all data passed to a template from a jQuery function by accessing Flask's DB query. I have a database table with customer names and phone numbers, which I pass to the template using Flask's view method "db ...

Turning backbone's collection toJSON method into a collection object

One of the attributes of my model is a backbone collection. When I print out the model, everything appears to be fine, including the collection. However, when I use the toJSON() method on the collection and output it, the entire collection object is disp ...

Storage in private Safari mode is not synced between tabs on mobile devices

In the private mode of mobile Safari, I have successfully stored data in the localStorage. However, when I open my web app in two separate tabs, I notice that the data stored in one tab is not accessible in the other tab. This behavior may be present in ot ...

The exported NextJS URL isn't functioning properly

Recently, I delved into the world of Next JS by following a tutorial on YouTube by Brad Traversy. In his guidance, I used next export to export the program and ran it using serve -s out -p 8000. While the page loads perfectly on localhost:8000, the issue a ...

Unraveling the mystery of decoding the yen symbol in JSON

In my Python code, I encountered an error while parsing a JSON file due to the character ¥. The specific error message I received was related to Unicode decoding: UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 106: inv ...

Watch mp4 clips in various languages with ExpressJs

I have a question regarding streaming videos within my local network. My mp4 files contain multiple audio tracks in different languages. Is there a way to select a specific audio track to stream? For instance, could you specify a language as a query parame ...

Issues with Jquery keyup on Android devices - unable to detect keyup

I have not tested this code on an iPhone, but I am certain (tested) that it does not work on Android mobile devices: $('#search').live('keyup',function(key){ if(key.which == 13){ /*ANIMATE SEARCH*/ _k ...

Unraveling the Mystery of Passing Props in React.js

Currently taking an online course to learn React, I encountered a unique scenario where one property is attached to another property in this manner: this.props.property01(this.props.property02) The tutor briefly touched on this code line, leaving me quit ...

Using lambda expressions to sort through an array of objects in React

My goal is to create a delete button that removes items from a list and updates the state variable accordingly. public OnDeleteClick = (): void => { const selectionCount = this._selection.getSelectedCount(); let newArray = this.state.items; for ...

changing a class to JSON format with nlohmann library in C++

Attempting to convert my class to json in visual studio 2017 is resulting in linker errors C2440. Severity Code Description Project File Line Suppression State Error C2440 'initializing': cannot convert from 'ns::person&apos ...