我是一名初學者,使用node.js,而且我似乎無法使其工作。Node.js http請求
function sleep(milliSeconds){
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + milliSeconds);
}
var isRequestComplete = false;
while(isRequestComplete == false){
console.log("in make request");
var querystring = require('querystring');
var data = querystring.stringify({
username: 'username',
password: 'password',
action: 'convert',
voice: 'engfemale1',
text: 'stuff and things, this should take longer than one request.'
});
var options = {
host: 'ws.ispeech.org',
port: 80,
path: '/api/rest/1.5',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length
}
};
var http = require('http');
var req = http.request(options, function(res) {
console.log("got response");
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
if(chunk.indexOf("finished") != -1){
isRequestComplete = true;
}
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(data);
req.end();
console.log("completed");
sleep(5000);
}
無論出於何種原因,http請求都不會發迴響應。除非代碼完全完成,否則在while循環中我永遠不會得到迴應。因此循環永遠不會結束。我的程序中輸入用戶名和密碼,這裏不是爲了保密。謝謝閱讀。
類似於http://stackoverflow.com/questions/10759638/using-a-json-file-to-store-a-small-database-persistently-in-javascript/10759692#10759692,這也涉及不適當的使用回調。 – apsillers 2012-07-31 15:33:45