0

I try to get the JSON data from a GET request and I can see the information from body in request. How can I get the data?

Currently use NodeJs, basic in JavaScript.

var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request') 

var information=[];
request({ 
    url: definedURL, 
    json: true 
}, function (error, response, body) { 

if (!error && response.statusCode === 200) {
    //console.log(body.result[0]);
    information.push(body.result[0]);
} 
});
console.log(information);

I expect after this I will see the contain of result coming out, but now it still shows [].

Leviand
  • 2,567
  • 3
  • 24
  • 35
Yixin Zhu
  • 47
  • 4
  • refer to this post: https://stackoverflow.com/a/983458/7688842 regarding GET requests. – MazBeye May 17 '19 at 08:08
  • You can get the body in request callback, `//console.log(body.result[0]);` uncomment this line. – hoangdv May 17 '19 at 08:09
  • simply because body in GET method is ignored. use POST method instead to use the body. You can still play around with the url's query string as well with POST method while accessing the body. – MazBeye May 17 '19 at 08:11

1 Answers1

0

Because you are making asynchronous request. Asynchronous action will get completed after the main thread execution.

console.log(information) // execute before your call

You need to wait for the request call to get completed and received data get pushed to information

There can be two ways to do this -

Async/Await- MDN Reference

var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request') 

var information=[];

async () => {
  await request({ 
      url: definedURL, 
      json: true 
  }, function (error, response, body) { 

      if (!error && response.statusCode === 200) {
          //console.log(body.result[0]);
          information.push(body.result[0]);
      } 
  });
  console.log(information)
}();

Promise MDN reference

var definedURL="https://api.etherscan.io/api?module=account&action=tokentx&contractaddress=0x6a750d255416483bec1a31ca7050c6dac4263b57&page=1&offset=100&sort=asc&apikey=YourApiKeyToken";
var request = require('request') 

var information=[];
var Promise  = new Promise((resolve,reject) => {
  request({ 
      url: definedURL, 
      json: true 
  }, function (error, response, body) { 
        if (!error && response.statusCode === 200) {
            //console.log(body.result[0]);
            information.push(body.result[0]);
            resolve()
        } 
  });
})

Promise.then(() => {
    console.log(information)
})
Satyam Pathak
  • 4,618
  • 1
  • 17
  • 43