0

How can I send the JSON object "data" returned by the npm module "blockchain.info" in the callback "onRequest". I want to write this data in the browser.

var http = require("http");
var blockchain = require('blockchain.info');
var blockexplorer = blockchain.blockexplorer;

var txAdress = 'b4b69abc03e4a801201e57ca57891002e5e756e85dde77a17deff0b107185a78';

blockexplorer.getTx(txAdress, function (err, data) {
   if (err) return console.error(err);
    console.log(data.size);  // works fine
});

var server = http.createServer(onRequest).listen(8888);

function onRequest(request, response) {
   response.writeHead(200, {"Content-Type": "text/html"});
   response.write('<h3>List of transactions</h3>');
   //response.write('<p>' + data.size + '</p>');  // data undefined!
   response.end();
}
jfjobidon
  • 327
  • 5
  • 18

1 Answers1

0

data doesn't exist in the scope of onRequest. Learn about variable scope.

getTx also appears to be an asynchronous function, you cannot simply "return" it from the callback (in case you wanted to try that). Read this question to learn about that.

A simple solution would be to make the call in the request event handler:

function onRequest(request, response) {

    blockexplorer.getTx(txAdress, function (err, data) {
       if (err) return console.error(err);
       response.writeHead(200, {"Content-Type": "text/html"});
       response.write('<h3>List of transactions</h3>');
       response.write('<p>' + data.size + '</p>');
       response.end();
    });

}

Of course you have to poperly handle the error case as well and might want to cache the response from getTx.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143