javascript - 如何从接口中的API读取JSON文件
问题描述
我想每 11 秒从 API 读取一个 JSON 文件并在界面中显示它
在我的情况下:接口服务器在 http://localhost:8080/ 处运行 API 在 http://localhost:8088/route (我需要每 11 秒刷新一次,因为参数会发生变化)
在 route.js 中:
var i=0;
var delayInms = 11000;
var myVar = setInterval(TempFunction, 1000);
function TempFunction() {
router.get('/', (req,res,next)=>{
var text =[
{"carspeed":[233+i,445+i,223+i,444+i,234+i]},
]
console.log(text);
res.status(200).json(text);
});
window.location.reload(true);
i++;
}
********问题是我收到此错误:
ReferenceError:未定义窗口
我还有一个问题:要读取 JSON(在 http://localhost:8088/route 中每 11 秒更新一次),我这样做了:在 car.vue 中:
<template>
.
.
<ul>
<li v-for="todo of todos" :key="todo.id">{{todo.text}}</li>
</ul>
.
.
</template>
其次是 :
<script>
import axios from 'axios';
const WorkersURL="http://localhost:8088/route";
export default {
data: () => ({
drawer: false,
todos:[]
}),
async created()
{
try
{
const res = await axios.get(WorkersURL);
this.todos=res.data;
}
catch(e)
{
console.error(e)
}
}
}
<script>
********第二个问题:它没有从 http://localhost:8088/route 读取 JSON 文件
解决方案
您需要确保您的服务器能够被运行在不同主机/域/端口上的网页访问。在您的情况下,服务器运行在与网页本身不同的端口上,因此您无法成功调用 XHR(这是 Axios 正在做的),因为默认情况下未启用 CORS(跨源资源共享)。您的服务器将需要设置适当的标头以允许这样做。具体来说,Access-Control-Allow-Origin 标头。请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
其次,要每 11 秒更新一次客户端,有几个选择。最简单的方法是让您使用 setInterval 每 11 秒通过 axios 调用一次:
async created()
{
try
{
const res = await axios.get(WorkersURL);
this.todos=res.data;
// set a timer to do this again every 11 seconds
setInterval(() => {
axios.get(WorkersURL).then((res) => {
this.todos=res.data;
});
}, 11000);
}
catch(e)
{
console.error(e)
}
}
有几个更高级的选项,例如服务发送事件(请参阅https://github.com/mdn/dom-examples/tree/master/server-sent-events)或 websockets (https://developer .mozilla.org/en-US/docs/Web/API/WebSockets_API)。这两个选项都允许您控制服务器而不是客户端的时间间隔。为此设置服务器时需要考虑一些事项,因此这些setInterval
选项可能最适合您的情况。
推荐阅读
- python - 与文件名匹配的子字符串列表 - python
- r - 从两个不同的数据集中减去列
- node.js - 只有一个 LIKE pr。Node.js 应用程序中的电影帖子
- python - 使用递归验证二叉搜索树
- python - BAT 文件在激活 kivy 脚本时自行终止
- flutter - 必须初始化不可为空的实例字段“categoryTitle”。尝试添加初始化表达式或生成构造函数来初始化它
- android - 如何在 Unreal Engine 5 EA cmd 上使用 VPN(关于 Failed to download any source lists error)?
- hpc - 客户端服务器无法从 HPC 获得最后响应
- go - 修复红黑树删除修复中的无限循环
- testing - 当我测试暗网预训练模型时没有边界框(NO-DETECTION RESULT)