我已经在nodeJs中编写了这段代码:
function ricarica() {
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
//console.log(json[11].nome_abbr);
//console.log(json[11].valore);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/valore', function(req, res){
res.json({ livello: json[11].valore });
});
}
});
}
我想每10分钟运行一次该函数,我已经看过setInterval,但是当我替换它时:
ricarica();
与此:
setInterval(function() {
ricarica();
}, 600000);
当我从我的网站上请求数据时,第一个我可以看到数据,但是它没有更新,第二个我收到消息“ Cannot GET / valore”;
我如何获取数据并每10分钟更新一次?
答案 0 :(得分:0)
尝试一下:
function updateData() {
ricarica();
}
function ricarica() {
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
//console.log(json[11].nome_abbr);
//console.log(json[11].valore);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/valore', function(req, res){
res.json({ livello: json[11].valore });
});
}
});
}
setInterval ( updateData, 600000 );
答案 1 :(得分:0)
我已在此模式下解决:
async function ricarica() {
while(true){
await sleep(120000);
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var json = JSON.parse(body);
var i;
for(i = 0; i< json.length && json[i].nome_abbr != "PS_Giud" ; i++);
console.log(json[i].nome_abbr);
//console.log(json[i].valore);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Accept, Content-Type, If-None-Match, X-If-None-Match");
res.header("Access-Control-Expose-Headers", "Location, Warning, Etag");
res.header("Access-Control-Allow-Headers", "Content-Type, If-None-Match, X-If-None-Match, Authorization");
res.header("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS");
next();
});
app.get('/valore', function(req, res, next){
res.json({ livello: json[i].valore });
});
}
});
}
}
我只需要调用一次