我有一个网页在Node.js中运行(我使用ejs
来使用WebStorm提供的默认文件夹设置来呈现页面)。目前,我跑node bin/www
它包含以下内容:Node.js页面刷新后重新运行页面(并生成新数据)
***preamble***
var app = require('../app');
var debug = require('debug')('tennis-geek:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
***rest of code***
这然后运行app.js
文件,该文件包含以下内容:
...
var predictions = require("./routes/predictions");
app.use("/predictions", predictions);
...
这就是问题所在。在此页面的javascript文件(routes/predictions.js
)中,我想要显示从两个远程源(www.source_json.com
和www.source_csv.com
)收集的信息(由于只有两个来源我决定同步执行Web请求)。这是我不希望最终用户能够访问的私人信息,所以我认为最好是将这些数据服务器端进行处理和合并,然后保存我希望用户能够看到的任何最终数据成javascript对象称为data_array
并经由发送到相应的页面ejs
(views/predictions.ejs
):
var express = require('express');
var router = express.Router();
var recline = ("reclinejs");
var papa = require("papaparse");
var request = require('sync-request');
//Now I collect the Data.
var res = request('GET', 'www.source_json.com');
var data_1_json = JSON.parse(res.getBody('utf8'));
res = request('GET', 'www.source_csv.com');
var data_2_json = papa.parse(res.getBody('utf8'), {header: true, skipEmptyLines: true}).data;
//Now I do some private number crunching on the data
var data_array = private_number_crunching(data_1_json, data_2_json);
//Now I send make this information available to the user's browser
router.get('/', function (req, res, next) {
res.render('predictions', {title: 'Predictions', data_from_js: data_array});
});
module.exports = router;
从约每20分钟的两个远程源改变所收集的数据。但是,当我刷新页面时,数据不会从两个数据源中重新收集(我已经使用一些时间戳验证了这一点)。 如何在每次请求页面时要求Node.js返回新鲜源数据?有没有一个update button
我可以在页面上创建,或者我可以添加一些JavaScript?目前,我可以刷新信息的唯一方法是重新启动服务器(CTRL + C
+ node bin/www
)。
到目前为止,我已经尝试使用setInterval
循环,while
循环,加入<% setTimeout('window.location.reload();', 20000); %>
。此外,我已考虑使用nodemon
来观察某些伪文件,该文件可能包含数据源上次更改信息的时间,然后在发生更改时重新启动服务器,但我想避免这种情况。
此外,我已经看过 “类似的” 主题:
- How do I force a page to refresh the data upon reload after entering new record
- node.js get new data without refresh
我已经重构代码到上述form(在router.get('/',...')之前定义'private_number_crunching()'函数,并且该函数在'router.get('/',...''外部正常工作,但是使用上面的代码在浏览器中给出了以下错误: 'undefined不是函数''TypeError:undefined不是函数' '在/Users/oliver/WebstormProjects/tennis-geek/routes/predictions.js:248:9',其中第248行是指'res.render('predictions'....);'。任何想法为什么它似乎不喜欢这个范围内的功能? (感谢@LiterallyIlliterate的回复) – oliversm
另外,在控制台中,它给出了这样的信息:'无法加载资源:服务器响应状态为500(内部服务器错误)'。 – oliversm
我已经更改了代码,变量中的“res”肯定是问题所在。 –