Having trouble retrieving data from a JSON object following a Node fetch request in JavaScript

When utilizing node fetch for my API GET operation, the code I employ is as follows:

var fetch = require('node-fetch');

const HttpProxyAgent = require('http-proxy-agent');
const HttpsProxyAgent = require('https-proxy-agent');

fetch('https://threemashery.rb.ipdesign.info/cit1/apigw/tibs/nbrmgmt/NumberManagementService/v1/RetrieveListDNForSelection?apikey=5w8anhcabembfp7tne67rhk8&userID=cpacadm&quantity=2&operatorId=3UK&orderNumber=ORD12341&numberCategory=Normal', {method: 'GET', agent: new 
HttpsProxyAgent('http://10.10.104.4:50683') })
.then(resRaw=>{

    return resRaw.text();


})
.then(resJson=>{

    console.log(resJson);

    console.log(resJson.Header);

})

Here are the results from both console log outputs:

{"Header":{"ActivityName_T":"AS_DNLogicalResource_NM","MsgType_T":"RESPONSE","msgName":"Error occured while processing request for List DN","Source":"RetrieveListDNLogicalResourceNM","ActivityStatusEnum_T":"FAILURE","ActivityStatus_T":"rcFailure","Timestamp":"2018-07-26T14:45:14.009Z","ProviderInfo":[{"name":"b08359a6-dea1-4e34-9c47-8d5971e1a9dd1532616302405","valueType":"rcFailure","description":"Order is being modified.","Value":{"CharacteristicValue":[{"value":"FAILURE"}]}}]},"Payload":{"NotificationDetails":[{"errorCode":"rcFailure","errorDescription":"Order is being modified."}]}}

undefined

I am encountering an issue where the first element returns undefined. Could someone provide assistance with this problem?

I have also attempted the following solution:

console.log(resJson);
    let res=JSON.stringify(resJson);
    console.log(res);

However, the output still appears like this:

{"Header":{"ActivityName_T":"AS_DNLogicalResource_NM","MsgType_T":"RESPONSE","msgName":"Error occured while processing request for List DN","Source":"RetrieveListDNLogicalResourceNM","ActivityStatusEnum_T":"FAILURE","ActivityStatus_T":"rcFailure","Timestamp":"2018-07-26T14:40:40.189Z","ProviderInfo":[{"name":"4463c84f-4d38-4173-8f11-3b82b2c539a51532616029573","valueType":"rcFailure","description":"Order is being modified.","Value":{"CharacteristicValue":[{"value":"FAILURE"}]}}]},"Payload":{"NotificationDetails":[{"errorCode":"rcFailure","errorDescription":"Order is being modified."}]}}


"{\"Header\":{\"ActivityName_T\":\"AS_DNLogicalResource_NM\",\"MsgType_T\":\"RESPONSE\",\"msgName\":\"Error occured while processing request for List DN\",\"Source\":\"RetrieveListDNLogicalResourceNM\",\"ActivityStatusEnum_T\":\"FAILURE\",\"ActivityStatus_T\":\"rcFailure\",\"Timestamp\":\"2018-07-26T14:40:40.189Z\",\"ProviderInfo\":[{\"name\":\"4463c84f-4d38-4173-8f11-3b82b2c539a51532616029573\",\"valueType\":\"rcFailure\",\"description\":\"Order is being modified.\",\"Value\":{\"CharacteristicValue\":[{\"value\":\"FAILURE\"}]}}]},\"Payload\":{\"NotificationDetails\":[{\"errorCode\":\"rcFailure\",\"errorDescription\":\"Order is being modified.\"}]}}"

Answer №1

Why is the result coming back as undefined when I attempt to retrieve the first element?

You mentioned using return resRaw.text(), so resJson contains the text from the response.

A basic string does not possess a Header property.

If you wish to parse the response as JSON and store the resulting object in resJson, you should use return resRaw.json().


I even attempted this:

let res=JSON.stringify(resJson);

This approach is incorrect. You are converting the string into JSON format, when you need to parse the JSON data into JavaScript.

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

Employing JavaScript Timer to automate paging in GridView: A step-by-step guide

I'm looking to automate the paging of a gridview on my page so that it displays the next 10 records every 10 seconds. How can I achieve this with client-side event triggering, given that I have already implemented manual paging on the Gridview? ...

Retrieve data from the api

Can someone provide the JavaScript code to loop through an API, extract the coordinates/address, and map it? Here is a simple demonstration of fetching the API data: const fetch = require("node-fetch"); fetch('url').then(function (resp ...

Automatically clear text input field after choosing a new radio button using jQuery

I am dynamically adding Radio button function RadioButton() { $.ajax({ type: "POST", url: "VPATransaction.aspx/SetRadioButton", data: "{}", contentType: "application/json; charset=utf- ...

The clear button in md-autocomplete with md-clear-button="true" does not appear on the screen

I am encountering an issue with the <md-autocomplete> component as demonstrated in this example: The <md-autocomplete md-clear-button="true"> feature does not seem to be functioning. I would expect a clear button (cross) to appear at the end o ...

Searching within an Angular component's DOM using JQuery is restricted

Want to incorporate JQuery for DOM manipulation within Angular components, but only want it to target the specific markup within each component. Trying to implement Shadow DOM with this component: import { Component, OnInit, ViewEncapsulation } from &apo ...

Deciphering the Latest Javascript Ternary Condition Protocol

I'm unfamiliar with this JavaScript condition syntax (!params?.q). While I understand the ternary condition, this one has me stumped. Can someone offer some insights or suggest what I should learn to better grasp similar conventions? Here is a snippe ...

Looking to showcase more detailed items within ng-repeat in AngularJS

Retrieve an object from the server that resembles the following structure: "courses": [ { "id": 1, "name": "piano", "classes": [ { "id": 1, "name": "piano1", }, { ...

Utilizing Next.js for dynamic routing with [[...slug.js]] allows for comprehensive URL handling and seamless 404 page display for links leading back to the homepage - a feature

In order to achieve a single dynamic route for handling all requests in this application, I have created a file called [[...slug]].js. Data loading is managed using getServerSideProps(), allowing for server-side rendering. Notably, there are no index.js fi ...

Presenting a Random Term from an Array in Dual Locations

<input type="button" id="btnSearch" value="Search" onclick="myFunction();" /> <div id="message"> <p></p> </div> <br> <div id="message"> <p></p> </div> <script type="text/javascript"&g ...

What is the best way to set up JSON offline caching?

I am currently in the process of developing an app for reading articles, similar to TechCrunch. The app fetches data from a server in JSON format and displays it in a UITableView, showing the article image, title, and author's name. When a user click ...

Having difficulty grasping the concept of MVC within the context of my website's code

I'm struggling to grasp the concept of utilizing model-view-controller in the context of my registration system. As far as I understand it, the view loads, displaying the registration HTML form to the user. Once the user submits the form, a JavaScript ...

Conceal a child div through the use of AJAX technology

Utilizing AJAX, I am loading pages on my website. Each page consists of two common div elements - the header div and the content div. When navigating from one page to another, I load the content div of the next page into the current page using the followin ...

The necessary data is missing in the scope of the callback function

I'm facing an issue with a callback function's variable losing its scope. Consider the following simplified array of two objects: const search = [{socket: new WebSocket('ws://live.trade/123')}, {socket: new WebSocket( ...

Transmit a document to the OpenAI API without the need to interact with the file storage system

Is there a way to send file data to the OpenAI API without directly accessing the file system? I have the file contents stored as a string and would like to bypass reading from the file system. The code provided in the OpenAI documentation involves reading ...

Utilizing AngularJS to filter prices within a specific range using a button

I am new to using angularjs and I am working on implementing a price range filter with nouislider for a list of products with different prices. I want the filtering to happen only after the user clicks on the filter button. Below is the HTML code for my " ...

How can I enable ongoing user input within Applab?

Currently, I am developing an app on code.org that allows users to input their subject scores and receive their corresponding grades. The final output includes the average score across all subjects. However, I have encountered a limitation where I can on ...

Having difficulty saving information in a .json file

I'm currently facing an issue with my ionic framework hybrid application. My goal is to save values from three input boxes into a 'data.json' file, and be able to retrieve or modify that data as needed, ensuring that the values persist even ...

How can I confirm in Lodash whether all properties in an array are equal even without a property to exclude?

Consider the following array of employee data: var service = [{ AssignedEmployeeInternalID: "8000000011", AssignedEmployeeUUID: "00000000-0001-1EE1-82C1-8379F1C4462E", BillableIndicator: true, BusinessPartnerFormattedName: ...

Setting up a div as a canvas in Three.js: Step-by-step guide

Is there a way to adjust the JavaScript in this three.js canvas example so that the scene can be contained within a specific div element on a webpage? Here is the example: https://codepen.io/PedalsUp/pen/qBqvvzR I would like to use this as the background ...

Modifying a text value within a JSON data structure

I've been attempting to modify a json file using a Laravel command. Within the file, there are certain product codes that I need to update. However, the code I've written doesn't seem to be working as expected - it executes without making an ...