Javascript Node.js在循环中发送http请求

Javascript Node.js在循环中发送http请求,javascript,node.js,Javascript,Node.js,实际上,我在使用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)

实际上,我在使用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);
}
var http=require('http');
变量选项={
主机名:“www.google.ca”,
港口:80,
路径:“/”,
方法:“获取”
};
函数sendRequest(选项){
log('hello');
var start=新日期();
var req=http.request(选项、函数(res){
log('Request take:',new Date()-start,'ms');
});
请求开启('错误',功能(e){
log('请求问题:'+e.message);
});
请求结束();
};

对于(var i=0;i可能是您的计算机或远程计算机被您同时发出的10个请求压垮了。尝试一次发送一个请求,您必须等到第一个请求完成后才能继续。一种简单的方法是


远程服务器的可能副本限制了并行请求的数量。请尝试串联发送这些请求。
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);