首页 > 解决方案 > 如何使用 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)
        }
    })
})

标签: javascriptnode.jsmongodbaxios

解决方案


我在下面的代码中添加了一些注释,但考虑到我放在那里的数据是硬编码的,你需要使用 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>


推荐阅读