The OpenWeatherMap API is displaying 'undefined' as a response

I've been encountering some issues with my weather app project due to lack of clarity in my previous questions. To be more specific, every time I attempt to retrieve weather information in JSON format using the fetch method, it keeps returning undefined. I'm building this app solely with pure vanilla JavaScript and utilizing Open Weather Map's API for data retrieval. I even tried switching to a different API (Free Weather API) but encountered the same issue with undefined responses. The websites themselves seem to be loading fine, leading me to believe that the problem lies within my code.

fetch('http://api.openweathermap.org/data/2.5/weather?q=Traralgon&appid=a211b9a621afd7714296d94616623dea&units=metric').then(function (response) {
    console.log('success!', response.main);
}).catch(function (err) {
    console.warn('Something went wrong.', err);
});

Answer №1

To effectively utilize the promise method, it is essential to manipulate the response and then transfer this modified data to the subsequent then function.

fetch(
    'http://api.openweathermap.org/data/2.5/weather?q=Traralgon&appid=a211b9a621afd7714296d94616623dea&units=metric'
  )
    .then(function (response) {
      return response.json();
    })
    .then(function (responseJSON) {
      console.log('success!', responseJSON.main);
    })
    .catch(function (err) {
      console.warn('Something went wrong.', err);
    });

For more information, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Answer №2

It is important to remember to utilize the json() method on the response object before performing any operations on the data. The json() method specifically takes a Response stream and reads it entirely, returning a promise. To handle the promise returned by response.json(), we should employ the .then() method. Once resolved, it parses the body text as JSON.

fetch('http://api.openweathermap.org/data/2.5/weather?q=Traralgon&appid=a211b9a621afd7714296d94616623dea&units=metric')
        .then(function (response) {
           // parsing the body of response object
            return response.json();
        })
        .then(function (response) {
            console.log('success', response.main);
        })
        .catch(function (err) {
            console.warn('Something went wrong.', err);
        });

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

Is there a way to show information exclusively on the selected card upon clicking?

[click here to see image 1] https://i.sstatic.net/cfvUT.png [click here to see image 2] https://i.sstatic.net/ISXAU.png Greetings, fellow beginners! Once again I find myself stuck on a coding problem. I have fetched various workout data and displayed t ...

Utilizing React Recharts to create personalized tooltips

In my current project, I am looking to create a custom tooltip to replace the default one in recharts. The default tooltip that I want to change is shown below: https://i.stack.imgur.com/TjTiL.png I would like the new custom tooltip to look like this: ...

The journey of data starting from a PHP file, moving through JavaScript, and circling back to PHP

I've encountered an interesting challenge with my PHP file and Wordpress shortcode. It all starts when the shortcode is embedded in a webpage, triggering a php function from within the file. This function executes an SQL query to extract data, then s ...

Incorporating CSS into React.js applications

I am currently working on a project using MERN.io. In my project, I am utilizing the React.js component Dropdown. However, the Dropdown component does not come with its own style and CSS, resulting in no styling at all. ... import Dropdown from 'rea ...

Are you in need of a JavaScript data validation tool?

Trying to find a library that can validate input in a specific format, such as: { points: array of { x: positive and less than 20, y: positive and less than 15 } } Ideally, it should work on both server and client sides and either return a boolean or th ...

locomotory mesh decentralized sorting

I am attempting to implement in-browser sorting for my flexigrid. Currently, the grid is displaying data from a static XML file exactly how I want it, but the table itself does not sort because it is working off of local data. While researching solutions, ...

What is the most efficient way to cycle through HTML image elements and display a unique random image for each one?

I'm currently working on coding a simple game that involves guessing the Hearthstone card based on its flavor text. I plan to add a button later to progress in the game, but I haven't implemented that yet. To start, I created 4 image elements an ...

"Learn the trick to effectively binding the mousewheel event in Blazor for seamless functionality on the Firefox

We are looking to implement code for a mouse wheel event on a div container. The code below functions correctly in browsers Edge and Chrome: <div id="scroll-container" @onmousewheel="MouseWheelEventHandler"> [...] </div> ...

Tips for efficiently updating state in recompose by utilizing setTimeout?

Curious to learn more about recompose, my journey began with a basic component: const timer: React.SFC<MyProps | any> = ({ seconds }) => ( <span>{ seconds }</span> ); I wanted to find a way to pass the seconds prop using recompose, ...

The values of the elements in the image array are null when not inside the

I need help converting an image into a Uint8Array for use in F5 steganography with the f5stego package. After trying to implement this, I encountered an issue where the imageArray contains all zeroes when printed outside the function, but inside it holds ...

Understanding how to use the 'this' variable in Vue components is essential for efficiently modifying DOM elements. Let's dive into a clarification on the usage of 'this'

Within my vue component, the structure is as follows: export default{ name: '', data: function () { return { var1 :{}, var2 : {}, ... } }, created: function () { this.methodName1() }, methods: { me ...

Managing unanticipated errors in Express while utilizing async/await mechanics

Consider this TypeScript code snippet: app.get('/test_feature', function (req: Request, res: Response) { throw new Error("This is the bug"); }); app.use(logErrors); function logErrors (err: Error, req: Request, res: Response, next: NextFun ...

Displaying items from an array is made easy thanks to the combination of mapGetters, VUEJS, vuex, and vuetify

My website has two main routes: one for the home page and another for a configuration panel. In the home page, there is a container displaying information such as date, time, current temperature, etc. Below that, there is another container where users can ...

Steps to set up datetimepicker with varying date ranges for several input fields

I am having trouble getting a new date range for each text box in my form. It seems to only return the date range from the last textbox, even though I have made the textbox IDs dynamic. I have both start and end dates for each textbox and I have calculated ...

Is JavaScript still running despite not displaying insecure items due to IE 8 security warning?

After a user completes a transaction on my site, the confirmation page displays Google conversion tracking code in a small JavaScript snippet. This code is located on my Wordpay callback page, which pulls data from the regular site (HTTP) to the Worldpay s ...

objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of ...

Display a specific message in a div when the input field is left empty

My goal is to create a div that mirrors the content of an input field. When I type "lalala" in the input, it should show up in the div, and this part is working fine. However, I also want the div to display "The input is empty" when the input itself is emp ...

Transmit JSON via ajax and retrieve parameters through request in JSP

Is there a way to send a JSON object via ajax (with Jquery) and retrieve all parameters from the request Object in JSP on the server side? This is my JS code: var request = new Object(); request.param1= "value1"; request.param2 = "value2"; $.ajax({ ...

Exploring geometric materials within the THREE.js framework

I'm currently working on creating a geometry in THREE.js: var dotGeometry = new THREE.Geometry(); dotGeometry.dynamic = true; var createDot = function (group, x, y, z){ group.vertices.push(new THREE.Vector3( x, y, z)); } var width = 300; var he ...

Hinting the type for the puppeteer page

I am trying to type hint a page variable as a function parameter, but I encountered a compilation error. sync function than_func(page:Page) ^ SyntaxError: Unexpected token: ...