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

后端 未结 7 1220
没有蜡笔的小新
没有蜡笔的小新 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:52

    This is my solution, although for sure you can use a lot of modules that give you the object as a promise or similar. Anyway, you were missing another callback

    function getData(callbackData){
      var http = require('http');
      var str = '';
    
      var options = {
            host: 'www.random.org',
            path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
      };
    
      callback = function(response) {
    
            response.on('data', function (chunk) {
                  str += chunk;
            });
    
            response.on('end', function () {
                  console.log(str);
              callbackData(str);
            });
    
            //return str;
      }
    
      var req = http.request(options, callback).end();
    
      // These just return undefined and empty
      console.log(req.data);
      console.log(str);
    }
    

    somewhere else

    getData(function(data){
    // YOUR CODE HERE!!!
    })
    

提交回复
热议问题