receiving an undefined value from a remote JSON object in Node.js

I have been struggling to extract the specific contents of a JSON api without success. Despite my best efforts, the console always returns undefined. My goal is to retrieve and display only the Question object from the JSON data. After spending several hours attempting different methods and scouring through resources online, I am finally seeking guidance on how to solve this issue.

var url = 'https://opentdb.com/api.php?amount=1&category=15&type=multiple';

https.get(url, function(res){
var body = '';

res.on('data', function(chunk){
    body += chunk;
});

res.on('end', function(){
    var trivapi = JSON.parse(body);
    console.log("Received response: ", trivapi[0].question);
});
}).on('error', function(e){
  console.log("Encountered an error: ", e);
});

Answer №1

Seems like you're on the right track, but make sure to include the results wrapper in your code. Check out the modified version below:

const https = require('https');
const url = 'https://opentdb.com/api.php?amount=1&category=15&type=multiple';

https.get(url, function(res){
    let body = '';

    res.on('data', function(chunk){
        body += chunk;
    });

    res.on('end', function(){
        const trivapi = JSON.parse(body);
        console.log("Received a response: ", trivapi.results[0].question);
    });
}).on('error', function(e) {
    console.log("Encountered an error: ", e);
});

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

When utilizing the `useLocation` hook, the location information appears to be missing

When utilizing a HashRouter, and inside a component making use of useLocation, there seems to be an inconsistency between the window.location object and the location object retrieved from useLocation. While writing this, I have observed that there might b ...

Presenting JSON information in a searchable table format with user-friendly pagination options

Greetings! I am looking for a way to showcase my JSON Data in a tabular format. Here is the sample JSON data I have: {"total":1,"per_page":6,"current_page":1,"last_page":1,"from":1,"to":1, "data":{"id":999, "firstName":"user999", "lastName":"lastna ...

Access JSON value using jQuery by key

Creating a JSON structure that contains information about attendees: { "attendees": [ { "datum": "Tue, 11 Apr 2017 00:00:00 GMT", "name": " Muylaert-Geleir", "prename": "Alexander" }, { "datum": "Wed, 12 Apr 2017 ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

Reading a Json file with keys in puppeteer BDD: A Guide

Greetings, I am new to the world of puppeteer. I have successfully created my basic framework and now I am trying to figure out how to read data from .json files. I attempted to use the readFile method in my helper class, but unfortunately, it resulted in ...

Accessing instance variables from a chained observable function in Angular 2/Typescript

Currently, I am utilizing Angular2 along with Typescript. Let's assume that there is a dummy login component and an authentication service responsible for token authentication. In one of the map functions, I intend to set the variable authenticated as ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

Preventing click propagation for custom react components nested within a MapContainer

I have developed a custom control React component for a map as shown below: export const MapZoom = () => { const map = useMap() const handleButtonClick = () => { map.zoomIn() } return ( <IconButton aria ...

Are there any conventional methods for modifying a map within an Aerospike list?

Attempting to modify an object in a list using this approach failed const { bins: data } = await client.get(key); // { array: [{ variable: 1 }, { variable: 2 }] } const { array } = await client.operate(key, [Aerospike.maps.put('array', 3).withCon ...

Using JQuery to enable checkbox if another is selected

I have a single checkbox that reveals a hidden div when checked. Inside this div, there are two additional checkboxes. My goal is to disable the initial checkbox if either of these two checkboxes is checked. Here's the HTML code snippet: <p> ...

Providing properties to the main Vue.js components

An Issue I'm Facing I am currently attempting to pass a prop to my root constructor. To achieve this, I have been exploring the use of propsData, which I learned about from this resource: var appComponent = Vue.component('app', require(&ap ...

Angular 2 with a jssor slider that adjusts seamlessly to different screen

After following the guidance provided in this answer on incorporating jssor into angular2, I have implemented the following JavaScript code snippet in a file and referenced it in angular-cli.json. jssor_1_slider_init = function() { var jssor_1_op ...

What is the recommended method for writing JavaScript scripts with AJAX in a Rails application? How can URLs be incorporated into the script effectively?

When incorporating AJAX into my Rails application, I encounter difficulties when specifying the URL for the request within a script. While it is recommended to use helpers like my_resource_path instead of manually writing paths, these helpers do not functi ...

Having trouble with object initialization in a jQuery GET request?

Looking to create an HTML button using jQuery that, upon clicking the chart button, will retrieve values from specified text inputs. These values will then be used to construct a JSON object which will subsequently be included in a GET request. $(".chart" ...

There was an unexpected error in angular.js while trying to work on a calendar widget based on angular-ui-calendar. The error message indicated that the argument 'fn' was expected to be a function but instead received Moment

I came across a similar topic earlier on Stack Overflow, but unfortunately, the issue wasn't resolved. So, I've decided to revisit this question and address it myself this time. In my app.js file, which is where my main module for the app is ini ...

Achieve a Smooth Transition: Utilizing Bootstrap 3 to Create an Alert Box that Fades In upon Click and Fades Out

Incorporating AngularJS and Bootstrap 3 into my web app, there is an "Update" button that saves user changes. Upon clicking the "Update" button, I aim to trigger and display bootstrap's alert box with the message "Information has been saved," followed ...

Form input using the div element (when clicked)

I am currently working on a page that connects to a database with user information. For each user, I am creating a separate div element so that there are 6 divs total (each representing a different user). My goal is to have the ability for a user to click ...

Update Refresh Token within Interceptor prior to sending request

I'm stuck on this problem and could use some guidance. My goal is to refresh a user's access token when it is close to expiration. The authService.isUserLoggedIn() function returns a promise that checks if the user is logged in. If not, the user ...

Using TypeScript: creating functions without defining an interface

Can function props be used without an interface? I have a function with the following properties: from - HTML Element to - HTML Element coords - Array [2, 2] export const adjustElements = ({ from, to, coords }) => { let to_rect = to.getBoundingC ...