【问题标题】:Node.js sending http request in a loopNode.js 循环发送 http 请求
【发布时间】:2014-02-14 17:00:19
【问题描述】:

我实际上遇到了使用 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);
}

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

【问题讨论】:

标签: javascript node.js


【解决方案1】:

也许您的机器或远程机器被您同时发出的 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);

【讨论】:

    猜你喜欢
    • 2013-04-10
    • 2012-03-27
    • 2023-03-24
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多