gpt4 book ai didi

javascript - 如何使用 NodeJS 不断更新网页?

转载 作者:行者123 更新时间:2023-12-03 04:38:51 24 4
gpt4 key购买 nike

我对 NodeJS 相当陌生,我想知道如何让我的 Node 服务器不断更新网页。

所以我正在做的是从 Twitter 获取推文,现在我只想将它们全部显示在一个基本网页上。在第一次运行期间,它看起来像这样:

Name: ap. Text: RT @APCentralRegion: Yevgeny Yevtushenko, Russian poet who focused on war atrocities, dies in Oklahoma Name: ap. Text: A week after hundreds attended anti-government protests in Russia, police arrest dozens at unauthorized rallies. ...

但是,大约一分钟的时间间隔后,我收到以下错误消息:

response.write("*********End of One Interval*********")
^
TypeError: Cannot read property 'write' of undefined

我的代码如下,请记住,当我在 createServer 中使用 tweet 函数时,它仍然显示出无法正确更新页面的相同行为,但是,终端窗口始终使用 console.log 正确更新

// Dependencies =========================
var
twit = require('twit'),
config = require('./config');

var http = require("http");
var url = require("url");

var Twitter = new twit(config);


// FAVORITE BOT====================
// Heavily modified from original tutorial.

var favoriteTweet = function(response, a, b){

var params = {
screen_name: a,
count: b,
// q: '#aprilfools, #aprilfoolsday', // REQUIRED
// result_type: 'recent', //recent tweets only.
//lang: 'en'
}

//console.log("Params: " + params.q);
// find the tweet
Twitter.get('statuses/user_timeline', params, function(err,data){

// find tweets
//console.log(data);
var tweet = data; //.statuses for actual tweets.
//console.log(tweet);


for(var result in tweet) {
response.write("Name: " + a + ". Text: " + tweet[result].text + "\n");
console.log("Resulting text: " + tweet[result].text);
console.log("Created At: " + tweet[result].created_at);
}

//console.log(tweet);
response.write("*********End of One Interval*********")
console.log("*********End of One Interval*********")
});
}

http.createServer(function(request, response) {

response.writeHead(200, {"Content-Type":"text/plain"});
var params = url.parse(request.url, true).query;

var a = params.name;
var b = parseInt(params.count);


// grab & 'favorite' as soon as program is running...
favoriteTweet(response, a, b);

// 'favorite' a tweet in every 1 minute
setInterval(favoriteTweet, 60000);


}).listen(9090);

最佳答案

您必须将参数传递到回调中。执行以下操作:

 setInterval(function(){
favoriteTweet(response,a,b)
}, 60000);

关于javascript - 如何使用 NodeJS 不断更新网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43170932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com