我使用这个函数从另一个服务器获取数据(它基本上是发送命令来运行python程序,它将输出写入远程计算机上的文本文件,然后返回txt文件的内容)。
const getServerStatus = () => { // returns result of of screen -ls
const commandQuery = "python3 /home/user/scripts/getServerStatus.py && cat /home/user/scripts/status.txt";
return fetch('http://10.0.0.253:3005/fetch', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
command: commandQuery
})
})
.then(res => {
return res.json();
})
.then(data => {
return data.status;
})
.catch(err => { // it catches when fatch fails (server is off)
return 'OFF';
});
};在用户访问主页时执行该函数。
app.get('/', checkAuthenticated, async (req, res) => {
const status = await getServerStatus()
.then(data => {
return data;
});
res.render('index.ejs', {
name: req.user.username,
title: 'home',
server_status: status
});
})它没有问题,它返回数据,主页呈现得非常快,但问题是,如果我不刷新网页一段时间(大概2-3分钟左右),大约需要8-10秒才能再次获取和渲染主页。我只是不知道问题出在哪里。我认为我的异步函数有问题,但我不确定。或者我的节点服务器在没有连接的情况下会像空闲模式一样运行?
我的/fetch端点
app.post('/fetch', (req, res) => {
exec(req.body.command,
function (error, stdout, stderr) {
res.send(JSON.stringify({status :stdout.replace(/\s/g, '')}));
console.log('[+] SERVER STATUS SENT');
if (error !== null) {
console.log('exec error: ' + error);
}
});
});发布于 2022-01-19 03:39:38
原来是硬件问题?如果我在不同的raspberry pi上运行节点项目,它不会这样做,而且运行完美,没有问题。
https://stackoverflow.com/questions/70762525
复制相似问题