【发布时间】: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