Node.js在循环中发送HTTP请求

5

我实际上正在使用node.js执行我的javascript代码时遇到问题。我需要循环发送http请求到远程服务器(在代码中设置为www.google.ca)。

以下是我的代码:

var http = require('http');

var options = {
    hostname: 'www.google.ca',
    port: 80,
    path: '/',
    method: 'GET'
};

function sendRequest(options){
    console.log('hello');
    var start = new Date();
    var req = http.request(options,function(res) {
        console.log('Request took:', new Date() - start, 'ms');
    });
    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });
    req.end();
};

for(var i=0;i<10;i++){
    sendRequest(options);
}

我遇到的问题是,无论我循环多少次,我只会得到前五个的响应。对于其余的请求,虽然函数sendRequest()被调用,但我没有收到任何响应或错误消息。然后程序终止。 但当我将主机设置为localhost时,它可以正常工作。 是否有人有解决这个问题的方法? 提前致谢!

可能是重复的问题:node.js http.get hangs after 5 requests to remote site - loganfsmyth
远程服务器限制并行请求的数量。尝试按顺序发送这些请求。 - umair
1个回答

4
也许是你的机器或远程机器在处理你发送的10个请求时不堪重负。尝试逐个发送请求,直到第一个请求完成后再继续。一种简单的方法是使用async.timesSeries
var http = require('http');
var async = require('async');

var options = {
  hostname: 'www.google.ca',
  port: 80,
  path: '/',
  method: 'GET'
};

function sendRequestWrapper(n, done){
  console.log('Calling sendRequest', n);
  sendRequest(options, function(err){
    done(err);
  });
};

function sendRequest(options, callback){
  //console.log('hello');
  var start = new Date();
  var req = http.request(options,function(res) {
    // I don't know if this callback is called for error responses
    // I have only used the `request` library which slightly simplifies this
    // Under some circumstances you can accidentally cause problems by calling
    // your callback function more than once (e.g. both here and on('error')

    console.log('Request took:', new Date() - start, 'ms');
    callback(null);
  });
  req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
    callback(err);
  });
  req.end();
};

async.timesSeries(10, sendRequestWrapper);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接