【问题标题】:HTTP requests in a loop循环中的 HTTP 请求
【发布时间】:2019-04-25 02:28:44
【问题描述】:

我正在尝试将请求对象循环发送到服务器 1000 次。问题陈述基本上是在模拟电影《办公空间》,从一堆银行账户中提取少量资金。

这是我迄今为止尝试过的:

var options = {
    host: 'localhost', 
    path: '/withdraw',
    port: '1234', 
    method: 'POST',
    headers: {'Content-Type' : 'application/json'}
}; 



function readJSONResponse(response){
   var responseData = ''; 
    response.on('data', function(chunk){
        responseData += chunk;
    }); 
    response.on('end', function(){
        console.log(responseData);
    }); 
}

var req = http.request(options, readJSONResponse); 


for( var i = 0; i < 1000; i++) {
    if(i % 2 != 0) {
        var data = {
            "amount": 0.001,
            "id": i,
            "token": dateToken
        };
    }
}

req.write(JSON.stringify(data));
req.end(); 

我希望从每个奇数帐户中取出 0.001。但是,当循环结束时,它只需要 0.001 从 id 为 999 的帐户中取出。我也尝试在 for 循环中调用 req.write,这给出了

_http_outgoing.js:595
    throw new ERR_INVALID_ARG_TYPE('first argument',
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Rec
eived type undefined
    at write_ (_http_outgoing.js:595:11)
    at ClientRequest.write (_http_outgoing.js:567:10)
    at Object.<anonymous> (C:\Users\rlken\OneDrive\Documents\Spring 2019\comp_246\bankhack\wit
hdraw.js:40:5)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)

【问题讨论】:

  • 你的 for 循环实际上并没有做任何事情。
  • 就像我说的那样,我尝试在 for 循环中执行 req.write,这给了我上面的错误。

标签: javascript node.js


【解决方案1】:

正如 p.s.w.g 所说,for 循环什么也不做。在 for 循环中,正在创建一个变量,然后什么都不做。 您还应该做的是每次您想要发出请求时,在 for 循环中启动它,以便每次都会发生新请求。我可以预料到的情况是仅发送最后一个请求的数据,因为这是在发送之前存储在变量数据中的最后一件事。 此外,如果您希望请求 ID 从 1 开始并以 1000 结束,则将 '

var options = {
    host: 'localhost', 
    path: '/withdraw',
    port: '1234', 
    method: 'POST',
    headers: {'Content-Type' : 'application/json'}
}; 

function readJSONResponse(response){
   var responseData = ''; 
    response.on('data', function(chunk){
        responseData += chunk;
    }); 
    response.on('end', function(){
        console.log(responseData);
    }); 
}

for( var i = 0; i < 1000; i++) {
    if(i % 2 != 0) {
        var data = {
            "amount": 0.001,
            "id": i,
            "token": dateToken
        };
        var req = http.request(options, readJSONResponse);
        req.write(JSON.stringify(data));
        req.end();
    }
}

【讨论】:

  • 做到了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
相关资源
最近更新 更多