0

In a node.js server, I am parsing a JSON response from a database, but while accessing the object it returns undefined.

How do I access the object and get my desired value for the particular key?

Request code

var jsonpass = {};
let url = 'http://localhost:3003/customer/2';
let gID = req.params.id;

request.get(url, (error, reponse, body) => {
    jsonpass = JSON.parse(body);
    console.log('body', body, '\njsonpass ', jsonpass);
    if (error) {
        console.log(error);
    }
});

Output

body {"message":"get single data","data":[{"CUSTID":2,"NAME":"Harsh Mundhada","EMAIL":"HARSH","DESCRIPTION":"HARSH","PHONENUMBER":"+917378456555","FREQUENCY":"harsh","DAYNMONTH":"HARSH","INVOICENUMBER":"HARSH","DISTINCTDATES":null}]}
jsonpass {
  message: 'get single data',
  data: [
    {
      CUSTID: 2,
      NAME: 'Harsh Mundhada',
      EMAIL: 'HARSH',
      DESCRIPTION: 'HARSH',
      PHONENUMBER: '+917378456555',
      FREQUENCY: 'harsh',
      DAYNMONTH: 'HARSH',
      INVOICENUMBER: 'HARSH',
      DISTINCTDATES: null
    }
  ]
}

when I am trying to print the JSON object, I am getting the result as undefined

console.log('\nmessage-\n',jsonpass["message"]);
console.log('\nmessage2-\n',jsonpass.message);
console.log('\nmessage3-\n',String(jsonpass.message));

Output

message-

 undefined

message2-

 undefined

message3-

 undefined

Why is it giving me undefined and how do I solve it?

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • well, I did define a `var jsonpass={}` and after your comment tried it with const but it is still giving undefined. – Sherlock-Holmes-2-2-1 May 02 '22 at 06:28
  • 1
    You cannot access `jsonpass` outside of the `request.get()` callback. Remove your global `var jsonpass = {};` declaration and start reading about how asynchronous code works. – Tomalak May 02 '22 at 06:44

1 Answers1

0

To make your variable global, you can use globalThis.

This will make your variable global!


To use it, you first need to remove the following line of code.

var jsonpass = {};

Then, you need to change the jsonpass re-declaration statement in the function to this.

globalThis.jsonpass = JSON.parse(body);

This will add the value of jsonpass to the global context.

After this, you can access it outside of the function with the value updated like this.

console.log(globalThis.jsonpass.message);

In conclusion, to add your variable to the global scope in JavaScript, you can use this code.

let url = "http://localhost:3003/customer/2";
let gID = req.params.id;

request.get(url, (error, reponse, body) => {
    globalThis.jsonpass = JSON.parse(body);
    console.log("body", body, "\njsonpass ", jsonpass);
    if (error) {
        console.log(error);
    }
});

// Not part of your code, but used for getting the message
console.log(globalThis.jsonpass.message);

This should fix your issue.

Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33