1

I am fairly new to node and javascript and I am having trouble storing the information from an HTTP request into an object which I can use outside of the request.

I am looping through another object to get the path for the HTTP request and trying to store the response in another object which can be used outside of the loop.

function apiRequest(){

    var options = {        
        hostname: 'us-central1-dpduk-s-test-d1.cloudfunctions.net',
        path: '',
        method: 'GET',
        headers:{
            Authorization: ' Bearer A416EB2A-5B7F-4A85-9E32-75CDB8F4F0F6'            
       }
    };

    for(var i = 0; i < jsonObj.length; i++){

        options['path'] = '/parcels/' + jsonObj[i].parcel_number;    

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

            var respones = '';       

            res.on('data', function(data){
               respones += data;
            })

            res.on('end', function(){
               var routesETA = JSON.parse(respones);

            });
        })
        res.end();    
    } 
}

I just keep running into routesETA not defined.

TheMisir
  • 4,083
  • 1
  • 27
  • 37
  • For anyone wonder how i got around this, I added a count variable to record how many times I did a http request and used that to access my object to insert the results of the request. – gavin dhaliwal Oct 21 '19 at 17:49

1 Answers1

1

That's because you're declaring the variable routesETA inside of a callback, if you want to use it outside the for loop you should declare it along with the options:

var options = {        
    hostname: 'us-central1-dpduk-s-test-d1.cloudfunctions.net',
    path: '',
    method: 'GET',
    headers:{
        Authorization: ' Bearer A416EB2A-5B7F-4A85-9E32-75CDB8F4F0F6'            
   }
}, routesETA;
Matheus Gomes
  • 434
  • 2
  • 11