1

I just want to take out the http response of "res.on("end", function...". "Dati" is always "undefined". Why?

I even tried returning the result of every function but nothing, can anyone help me out please? Thanks a lot


var dati;

function accesso() {


  var http = require("http");

  var options = {
    "method": "POST",
    "hostname": "xxx.xxx.xxx.xxx",
    "port": "xx",
    "path": "/",
    "headers": {"
    }
  };

  var req = http.request(options, function (res) {

    var chunks = [];

    res.on("data", function (chunk) {
      chunks.push(chunk);
    });

    res.on("end", function () {

      var body = Buffer.concat(chunks);
      var response = body.toString()
      obj = JSON.parse(response)
      dati = obj.session

    });
  });

  req.write("{xxxxxxxxxx}");
  req.end();
}



aesign
  • 11
  • 1
  • *""Dati" is always "undefined". Why?"* Assuming taht `obj.session` is not `undefined`, `dati` will not be `undefined` **once the call completes.** But if you use it *before* the call completes, yes, it'll be `undefined` because nothing has ever assigned a value to it. See the linked question's answers for details. – T.J. Crowder Oct 06 '19 at 11:44
  • Have you tried putting a breakpoint at `obj = JSON.parse(response)`, or putting `console.log(response)` just before that line, to see what the value of `response` is? – kshetline Oct 06 '19 at 11:49

0 Answers0