How to get data out of a Node.js http get request

后端 未结 7 1186
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 23:25

I\'m trying to get my function to return the http get request, however, whatever I do it seems to get lost in the ?scope?. I\'m quit new to Node.js so any help would be appr

7条回答
  •  有刺的猬
    2020-11-28 23:33

    Of course your logs return undefined : you log before the request is done. The problem isn't scope but asynchronicity.

    http.request is asynchronous, that's why it takes a callback as parameter. Do what you have to do in the callback (the one you pass to response.end):

    callback = function(response) {
    
      response.on('data', function (chunk) {
        str += chunk;
      });
    
      response.on('end', function () {
        console.log(req.data);
        console.log(str);
        // your code here if you want to use the results !
      });
    }
    
    var req = http.request(options, callback).end();
    

提交回复
热议问题