【发布时间】:2019-12-31 15:45:02
【问题描述】:
我正在尝试将使用 fetch-api 提取的 json 对象发送到 EJS 文件,该文件在有人访问网站时加载。问题是我发现发送的对象在页面加载时未定义,因为获取数据需要一些时间。
我可以用异步包装 res.render 并等待等待获取数据然后渲染页面,但这会减慢网站加载时间。我希望 ejs 文件中有一个默认值,直到获取来自 api 的那个。
//One of the routes
router.get("/", (req, res) => {
fetchData(object => {
res.render("landingPage", { obj: object });
})
});
function fetchData(callback){
fetch("http://localhost:3000/api/teachers") //Could change this to a find request to the data base directly like Teacher.find()...
.then(res => res.json())
.then(res => {
return callback(res);
})
.catch(err => {
console.log(JSON.stringify(err));
});
}
<!--In the HTML file-->
<h5><%= obj.someValue %></h5>
在我提供的代码中,服务器等待获取数据然后呈现页面。我希望页面加载,并在提取完成后将提取的对象添加到页面。我怎么能这样做?
【问题讨论】:
标签: javascript html node.js express ejs