0

我试图用 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
4

1 回答 1

0
  1. 当传递一个Object作为第一个参数时,URL 应该被分解成单独的部分:

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

    使用的options包含在 下https.request(),这https.get()是 的一个方便变体。

    您还可以传递 URL Stringhttps.get()它将为您运行url.parse()

    var _request = https.get(url, ...);
    
  2. JavaScript 没有块范围的变量(尚未)。因此,尽管有 的位置,但循环var body = "";的每次迭代while仍然附加到相同的body.

    This isn't as much a concern when the variable is only used by synchronous tasks, like scanitem, url, and options are. But, when mixing in asynchronous tasks like https.get(), you won't likely get the result you're expecting.

    In the current absence of block-scoped variables, you can use a closure to create an additional function scope.

    As List appears to be an Array, you can use an iterator function with .forEach() for this:

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

    And, for the Limit, you can use .splice() to remove and work with the portion of the Array you want:

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

Also, unlike with https.request(), you're not required to call _request.end() when using https.get().

于 2013-07-03T20:55:55.903 回答