Node.js在循环中发送http请求 [英] Node.js sending http request in a loop

查看:205
本文介绍了Node.js在循环中发送http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm actually facing a problem with my javascript code executed with node.js i need to send http requests in a loop to a distant server (i set www.google.ca in the code). Here is my code :

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设置为主机时,它工作正常。
有人能解决这个问题吗?
提前致谢!

The problem I have is that, no matter how many times i go through my loop, i get a response for only the 5 first of them. For the rest of the requests, the function sendRequest() is called but I don't get any responses, neither error message. And then the program terminates. However it works fine when I set localhost as a host. Is anyone would have a solution to this problem ? Thanks in advance !

推荐答案

您的机器或远程机器可能会被同时发出的10个请求所淹没。尝试一次发送一个,您必须等到第一个请求完成后再继续。一个简单的方法是 async.timesSeries

perhaps either your machine or the remote machine is getting overwhelmed by the 10 simultaneous requests you make. try sending them one at a time, you will have to wait until the first request completes before continuing. one easy way to do so is with 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);

这篇关于Node.js在循环中发送http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆