The API response in JSON format is displaying as "undefined"

My current code is running as follows:

const request = require('request')
const apiKey = 'XXXXXXXXXXXXXX'

var dat;
let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx'
let qs = {
    q: '-34.48,150.92',
    format: 'json',
    apiKey
}
request({ url, qs }, (err, response, body) => {
    if (err)
        return console.error(err)
    if (response.statusCode != 200)
        return console.error('status code is', response.statusCode)
    body = JSON.parse(body)
    dat = body.data.hourly[0].tempC


})
console.log(dat);

I am anticipating a result of 15 from the API I am using because it should return:

{
"data": {
    "request": [],
    "weather": [{ 
        "date": "2016-11-20",
        "astronomy": [],
        "maxtempC": "27",
        "maxtempF": "80",
        "mintempC": "15",
        "mintempF": "58",
        "hourly": [{
            "time": "0",
            "tempC": "15",
...

However, instead of getting the expected value of Undefined. Why is this happening? Any help would be greatly appreciated. Thanks.

Answer №1

Make sure to place the console.log statement inside the callback function to ensure it runs after the data is retrieved from the server.

const request = require('request')
const apiKey = 'XXXXXXXXXXXXXX'

var dat;
let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx'
let qs = {
q: '-34.48,150.92',
format: 'json',
apiKey
}
request({ url, qs }, (err, response, body) => {
if (err)
return console.error(err)
if (response.statusCode != 200)
return console.error('status code is', response.statusCode)
body = JSON.parse(body)
dat = body.data.hourly[0].tempC
console.log(dat);
})

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

Angular Chart.js is throwing an error: "Uncaught SyntaxError: Cannot use import statement outside a module"

Upon opening the page, an error in the console related to Chart.js 4.2.1 is being displayed. Description of first image. Description of second image. Is it possible that this issue solely lies with Chart.js? How can it be resolved? To address the proble ...

Begin the jQuery ResponsiveSlides Slider with the final image in the <ul> list

Currently utilizing the responsiveSlides image slider from responsiveSlides on our website. This jQuery slider uses an HTML unordered list of images to slide through automatically. The issue I'm facing is that before the slider actually starts (meani ...

Utilizing CSS transitions to smoothly adjust the width of an element until it completely fills the container div in ReactJS

import React from 'react'; import PropTypes from 'prop-types'; import SearchIcon from '@material-ui/icons/Search'; import InputBase from '@material-ui/core/InputBase'; import { AccountCircle } from '@material-ui ...

Strange occurrences happen where objects are duplicated in the ArrayList when the debugger tool's 'step over' feature is used

Explaining this code is a bit challenging but it's designed to add items from a JSON array and display them on a ListView. The page refreshes using the onResume method that I have customized. public void onResume() { super.onResume(); if (a ...

express.js creating dynamic URLs causing confusion

router.get('/:username', function(req, res, next) { res.render('dashboard'); }); router.get('/', function(req, res, next) { if(req.user) // this has value res.redirect('/'+req.user); }); I'm experi ...

What is the best way to merge two similar arrays of objects into one array object?

Apologies in advance if this question has been asked previously, I'm struggling with how to phrase it. Essentially, the API I'm using is returning an array of similar objects: const response.survey = [ { 1: { id: 1, user: user_1, points: 5 ...

Converting Wordpress JSON data into a UITableView for iOS development

Having trouble parsing a JSON from this specific URL, which is an output in JSON format from Wordpress. Struggling to display the data in a UITableView. The code I currently have for parsing the JSON seems to be missing something, particularly when it com ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

A guide on sorting JSON data with Javascript/jquery

I have a set of JSON data: {"X1":"3","X2":"34","Y1":"23","Y2":"23","Z1":"234","Z2":"43",...} My goal is to rearrange and group this data as follows: var newDataJson1 = { "X":{"X1":"3","X2":34}, "Y":{"Y1":"23","Y2":"23"}, ... } ALSO, I want to stru ...

Searching for image labels and substituting the path string

Upon each page load, I am faced with the task of implementing a script that scans through the entire page to identify all image src file paths (<img src="/RayRay/thisisianimage.png">) and then add a specific string onto the file paths so they appear ...

What are the steps to standardize a JSON document using pandas?

I am looking for a way to restructure a JSON file that has the following format: [{ "ID":1, "Rev":2, "Fields":{"System.Id":1, "System.State":"Closed", "System.Title":"ABC", &qu ...

Inserting additional information and assigning a category following a prosperous AJAX request accompanied by output from php echo

I'm currently working on implementing an AJAX call to my PHP file to send an email once a contact form is submitted. Initially, I had everything functioning properly where the response from PHP was displayed in a div above the form. However, I wanted ...

Encountering a missing value within an array

Within my default JSON file, I have the following structure: { "_name":"__tableframe__top", "_use-attribute-sets":"common.border__top", "__prefix":"xsl" } My goal is to add values by creating an array, but I am encountering an issue where my ...

Having trouble with request-promise in node.js? It's not functioning as anticipated

Currently utilizing the request-promise node module. Following the documentation closely to ensure correct setup, however encountering the following error: Unhandled rejection StatusCodeError: 400 - "{\n \"error\" : {\n \"s ...

Is there a way to modify an npm command script while it is running?

Within my package.json file, I currently have the following script: "scripts": { "test": "react-scripts test --watchAll=false" }, I am looking to modify this script command dynamically so it becomes: "test&qu ...

Is there a way to make this eval() function function properly in Internet Explorer?

My JavaScript code is fetching another JavaScript "class" from a different XHTML page. The fetched JavaScript looks like this: (function() { this.init = function() { jQuery("#__BALLOONS__tabs").tabs(); }; }) Once the f ...

ES5 approach to Angular2 HTTP Providers (not TypeScript)

I'm currently developing an application and experimenting with Angular2 using ES5 JavaScript for fun. My main inquiry right now is how to access the Http service. Most of the available documentation is in TypeScript, which is not very helpful, or it p ...

Retrieving data from MySQL and mapping it to a model class in Android Studio

After numerous attempts to add the COUNT rows of a MySQL table to the ModelCLass, I finally found a method that seemed promising. However, I am encountering an error and struggling to identify where I went wrong. Any assistance would be greatly appreciated ...

A guide to organizing elements in Javascript to calculate the Cartesian product in Javascript

I encountered a situation where I have an object structured like this: [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name ...

Can anyone guide me on successfully converting SQL Server data to JSON format in real-time using ASP.NET and Visual Studio?

My main objective is to continuously export data from MS SQL server in real-time and convert it into JSON format. This JSON data will then be used to generate a dynamic line graph on the front end using AM Charts Dataloader. The goal is to keep the line gr ...