我想将JSON数据从nodefetchapi发送到浏览器,并每900毫秒更新一次数据.我该怎么做



我有一个问题,我想向客户端发送响应。我用Express.js编写了一个服务器,创建了所有的路由,并将所有的东西连接在一起。我的默认视图引擎配置为EJS。我不想只将值记录到控制台,但我也想将其发送到客户端并动态更新。希望这是有道理的。

我在这里有我的node-fatch API代码:

const express = require("express");
const fetch = require("node-fetch");
const router = express.Router();
router.get("/", (req, res) => {
res.send("API ONLINE")
})
function issFetch() {
fetch("http://api.open-notify.org/iss-now.json")
.then((response) => {
return response.json();
})
.then((json) => {
console.log(json);
res.send(json)
})
.catch((e) => {
return JSON.stringify(e);
});
}
setInterval(issFetch, 900)
module.exports = router;

我的EJS文件在这里

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ISS Live Location API - Michael Grigoryan</title>
</head>
<body>
<pre>
<code lang="json">
<%= data %>
</code>
</pre>
</body>
</html>

服务器发送事件(SSE(/EventSource是此作业的工具。

客户端请求流,然后事件发生时从服务器发送到客户端。

不需要web套接字也不需要Socket.IO。这是单向通信。。。不需要额外的一层。当然,我不会使用投票,因为这会带来大量开销。

另一种选择是在客户端进行计算,因为您正在跟踪轨道。这样,您只需提前发送少量数据,并且当前位置可以实时直播,而无需流式传输数据。

最新更新