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

Loading scripts dynamically with async/await in JavaScript

I may be committing a typical beginner error. Aim I have a script named loader.js, where I intend to provide a collection of JavaScript files that control the shape, size, and position of components. The structure of the file is as follows: const loadSc ...

What could be the reason for the lack of error handling in the asynchronous function?

const promiseAllAsyncAwait = async function() { if (!arguments.length) { return null; } let args = arguments; if (args.length === 1 && Array.isArray(args[0])) { args = args[0]; } const total = args.length; const result = []; for (le ...

The ReactJS Application Cache Client fails to display the most recent updates

One issue I'm currently facing is with my application in production. Some clients have reported that they are unable to see the new changes unless they clear their cache completely. Using Techs: React Any suggestions on what steps I should take to a ...

Converting JSON information into a mailto hyperlink

Can anyone help me figure out how to encode a mailto link properly with JSON data in the query parameters, ensuring that it works even if the JSON data contains spaces? Let's consider this basic example: var data = { "Test": "Property with spaces" ...

Retrieving a universal variable within AngularJS

Is there a way to initialize an Angular model using a JSON object that is embedded within an HTML page? Take this as an example: <html> <body> <script type="text/javascript" charset="utf-8"> var tags = [{&q ...

Not triggering onDragStart in Material UI Autocomplete component in React

I'm facing an issue with an onDragStart handler in a React Autocomplete component. Despite adding the handler, it fails to trigger when dragging using the mouse. You can explore a live demo of this problem here: https://codesandbox.io/s/material-demo- ...

Angular JS is encountering an issue where the promise object is failing to render correctly

I'm currently learning Angular and I have a question about fetching custom errors from a promise object in Angular JS. I can't seem to display the custom error message on my HTML page. What am I missing? Below is my HTML file - <!DOCTYPE htm ...

What is the best way to dismiss the additional modal popup?

Here is an example that I need help with: http://jsfiddle.net/zidski/Mz9QU/1/ When clicking on Link2 followed by Link1, I would like the Link2 box to close automatically. Is there anyone who can assist me with this issue? ...

Stream-Awesome #12: The Return of Duplexer in Nodesville

For days, I've been attempting different methods to solve this exercise. It's frustrating because no matter what I try, I keep encountering a "write after end" error. But here's the thing - I'm using the "end" event and not writing anyt ...

Tips for preventing the use of eval when invoking various functions

Here's a snippet of code I've been using that involves the use of eval. I opted for this approach as it seemed like the most straightforward way to trigger various factory functions, each responsible for different web service calls. I'm awa ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...

The Vanilla JS script in Next.js fails to execute upon deployment

Currently developing a simple static site with Next.js. The lone vanilla JS script in use is for managing a mobile menu - enabling toggling and adding a specific class to disable scrolling on the body: if (process.browser) { document.addEventListener(&ap ...

Managing errors in Node.js when inserting data into MongoDB

Hello everyone, I'm currently working on handling errors in the user signup module using Express. However, I'm facing an issue where the errors are not being handled correctly. Here is my code: handler.post(async (req, res) => { let otp = M ...

Learning the process of connecting functions to events

// param {id:'buttonId', action : function(event[,param1, param2] ){}, behavior:function(event[,param1, param2] ){} } CustomButton = function(parameters) { var buttonElement = document.getElementById(parameters.id); // how c ...

ES6 Generators: lack of informative stack trace when using iterator.throw(err)

The ES6 approach: iterator.throw(err) is often explained as inserting an exception as if it happened at the yield statement within the generator. The challenge lies in the fact that the stack trace of this exception does not include any information about t ...

Error encountered during navigation: navigator has not been defined

I encountered an issue where the page gets redirected upon form submission without triggering the catch block. However, in the backend, I am facing an error stating that the API body is not being executed. Below is the code snippet of the page: "use cl ...

Trouble resolving a timer interruption in JavaScript

Creating dynamic elements using PHP has brought me to a new challenge. I want to implement a functionality where the user can hover over an icon and see the related element, which should disappear after some time if the mouse leaves the icon. Additionally, ...

Switch between clicking and hiding

I am currently working on data tables and have successfully loaded my table via ajax, which also populates a new row drop down. However, I am experiencing an issue where I can get the row to drop down but cannot get it to close again. It simply adds the ...

Unraveling the intricacies of extracting data from nested object properties

Why do my variables stop being reactive after unwrapping from props? I have three components - a parent component, a second component for display, and a third component for updating data based on input (simplified code here). The third component updates ...

Emphasizing the date variable within a spreadsheet

Hey there! I'm struggling with the code below: <html> <head> <title>highlight date</title> <style> .row { background-color: Yellow; color:blue; } </style> <script type="text/javascript"> </script> &l ...