javascript - 如何使用 Node.JS 将 MongoDB 数据集合显示到 index.html 页面
问题描述
我试图修复我的后端并用 重写我的“get”路由res.render(data)
,但它仍然没有用。
请举例说明如何做到这一点。
另外,我在前端部分使用 Axios。
我的获取路线:
app.get('/',(req,res) => {
console.log('Welcome to roffys server')
Todo.find({}).exec((err,todo)=>{
if(err) {
console.log('Error retrieving todos')
} else {
res.json(todo)
}
})
})
解决方案
我在下面的代码中添加了一些注释,但考虑到我放在那里的数据是硬编码的,你需要使用 getTodo 函数获取数据。
const dataFromAPI = [
{todo: "do homework", status: "complete"},
{todo: "Read a book", status: "incomplete"}
]
const rootApp = document.getElementById("app");
function getTodo () {
// Since I don't will do a call to a API, I comment this, but you need it in your environment.
//fetch("someUrl")
//.then(res => res.json())
//.then(addDataToHtml) addDataToHtml is a function that will receive your data as argument
}
function addDataToHtml(data) {
data.forEach(task => (
rootApp.innerHTML += `
<div>
<div>
<span>Task:</span>
<span>${task.todo}</span>
</div>
<div>
<span>Status:</span>
<span>${task.status}</span>
</div>
</div>`
))
}
// I do the call here, but you need to do it in the getTodo function.
addDataToHtml(dataFromAPI);
<div id="app"></div>
推荐阅读
- javascript - 如何将按钮和文本放在同一行?
- pytorch - 如何通过 Pytorch 和 Optuna 进行交叉验证
- flutter - Flutter - 如何获取画廊文件夹路径?
- go - 全局变量的值是否在多个 API 调用中保持不变
- docker - Docker 上 Quarkus 和 Keycloak 的配置
- ios - 快速滑出带有子类别的栏
- sql - sql删除重复行
- reactjs - 为什么Pressable组件的涟漪效应只在长按时触发
- modbus - 使用 Python / ModBUS 从 Carlo Gavazzi EM24-DIN.AV5 读取寄存器时出现问题
- amazon-web-services - AWS Amplify:更改身份验证资源名称