我希望创建第一个节点js app。为此,我需要将公共Twitter推文和输出推文作为请求响应。我搜索了很多,但我得到的代码是用较旧的节点版本代码编写的(即createServer,addListener就像这样)。我们如何编写请求twitter调用的代码并在节点版本0.6.18中输出json作为响应?
以下是我尝试的旧代码
var http = require("http");
var events = require("events");
var port = 8001;
var twitterClient = http.createClient(80, 'api.twitter.com');
var tweetEmitter = new events.EventEmitter();
var request = twitterClient.request("GET", "/1/statuses/public_timeline.json", {"host": "api.twitter.com"});
function getTweats() {
request.addListener("response", function (response) {
var body = "";
response.addListener("data", function (data) {
body += data;
});
response.addListener("end", function (end) {
var tweets = JSON.parse(body);
if (tweets.length > 0) {
tweetEmitter.emit("tweets", tweets);
console.log(tweets, 'tweets loaded');
}
});
});
request.end();
}
setInterval(getTweats(), 1000);
http.createServer(function (request, response) {
var uri = url.parse(request.url).pathname;
console.log(uri);
if (uri === '/stream') {
var cb = function (tweets) {
console.log('tweet'); // never happens!
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(JSON.stringify(tweets));
response.end();
clearTimeout(timeout);
};
tweetEmitter.addListener("tweets", cb);
// timeout to kill requests that take longer than 10 secs
var timeout = setTimeout(function () {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(JSON.stringify([]));
response.end();
tweetEmitter.removeListener("tweets", cb);
}, 10000);
} else {
loadStaticFile(uri, response);
}
}).listen(port);
console.log("Server running at http://localhost:" + port + "/");
得到错误
$ node tweet.js
Server running at http://localhost:8001/
timers.js:223
callback.apply(timer, args);
^
TypeError: Cannot call method 'apply' of undefined
at Timer.ontimeout (timers.js:223:14)
答案 0 :(得分:1)
您的错误很常见。而不是:
setInterval(getTweats(), 1000);
你需要
setInterval(getTweats, 1000);
这是因为您希望setInterval
调用getTweats
函数本身。
您的代码的getTweats()
代替括号。此首先调用 getTweats
,并将结果提供给setInterval
。由于此结果为undefined
(您的函数不返回任何内容),因此节点无法调用它。