2013-07-03 54 views
0

我試圖讓一個循環與http.get請求 - 我不知道爲什麼函數不啓動。 我的代碼是:節點http.get沒有解僱

while(List.length>0) {     
    if(counter < Limit) { // Limit is the amount of requests I want to 
     counter++; 
     inProcess++; 
     var scanitem = List.pop(); 

     var body = "";  
     var url = 'https://www.mywebsite.com/'+scanitem; 
     var options = { 
         path: url,             
         method: 'GET' 
        }; 
     console.log(url); // This part is happenning 
     var _request = https.get(options, function (res) { 
         console.log('get web site');// this part is NOT showup. 
         res.on('data', function (chunk) { 
          console.log(chunk); // this part is NOT showup. 
          body += chunk.toString();    
         }); 
         res.on("end", function() {        
         console.log(body);// this part is NOT showup. 
         }); 
         res.on("error", function(error) {       
         console.log('error')// this part is NOT showup. 
         }); 
        }); 
     _request.end();   
    }           
    else { 
     console.log('list BREAK');} // This part is happenning after the limit crossed 
+0

您可以首先添加'_request.on(「error」,function(error)'來找出任何錯誤,因爲如果在發送任何響應之前請求本身可能失敗,則不會顯示響應錯誤。 – user568109

+0

https請求可能因爲你沒有給任何服務器可能拒絕請求本身 – user568109

回答

0
  1. 時傳遞一個Object作爲第一個參數,該URL應該被分解成各個片:

    var options = { 
        method: 'GET', 
        protocol: 'https:', 
        hostname: 'www.mywebsite.com', 
        path: '/' + scanitem 
    }; 
    
    var _request = https.get(options, ...); 
    

    所使用https.request()下覆蓋的options ,其中https.get()是一個方便的變種。

    您也可以通過URL String,這https.get()將通過url.parse()爲您運行:

    var _request = https.get(url, ...); 
    
  2. JavaScript沒有塊作用域的變量(yet)。因此,儘管var body = "";的位置,您的while循環的每個迭代仍然追加到相同的body

    當變量僅用於同步任務時,這不是一個值得關注的問題,如scanitemurloptions。但是,當混合像https.get()這樣的異步任務時,你不可能得到你所期望的結果。

    在當前沒有塊範圍變量的情況下,可以使用closure創建另一個function範圍。

    至於List似乎是一個Array,你可以使用一個迭代器function.forEach()此:

    List.forEach(function (scanitem) { 
        var body = ''; 
        var url = 'https://www.mywebsite.com/'+scanitem; 
    
        https.get(url, function (res) { 
         // etc. 
        }); 
    }); 
    

    而且,爲Limit,您可以使用.splice()刪除,並與Array的部分工作你想:

    List.splice(0, Limit).forEach(function (scanitem) { 
        // etc. 
    }); 
    

此外,與https.request()不同,在使用https.get()時,不需要撥打_request.end()

+0

仍然無法正常工作,當我把它從循環中取出時,它的工作正常,但是當它的一部分進程 - 它不知道怎麼做, t開始請求。 – ItayM