簡體   English   中英

如何使用 Node.JS 將 MongoDB 數據收集顯示到 index.html 頁面

[英]How to display MongoDB Data collection to the index.html page using Node.JS

我試圖修復我的后端並用res.render(data)重寫了我的“get”路由,但它仍然不起作用。

請舉例說明如何做到這一點。

另外,我在前端部分使用 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 function 獲取數據。

 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM