2017-12-27 835 views
2

所以我正在學習nodejs和mongodb。我使用expressjs和mongojs作爲後端應用程序的前端和ejs。我想要做的是用戶將從下拉列表中選擇以查看可用類的列表,並且類的列表將顯示在表中。例如,如果用戶選擇全部,則數據庫中的所有類都將顯示在表中。我不確定如何從下拉菜單中獲取值,並以表格形式顯示來自MongoDB的數據。這是我到目前爲止,我得到此錯誤:錯誤:發送後無法設置標頭。從下拉列表中獲取值顯示錶nodejs

admin.js

router.get('/showclass', function(req, res) { 
    res.render('showclass'); 
}); 
router.post('/showclass', function(req, res) { 
    var selectValue = req.body.table; 
    if(selectValue == 'all') { 
     console.log('All is selected'); 
     db.classes.find().forEach(function(err, doc) { 
      if(err) { 
      res.send(err); 
      } else { 
       res.send(doc); 
       res.render('showclass'); 
      } 
     }); 
    } 
}); 

EJS

<%- include('includes/header') %> 
<%- include('includes/navbar') %> 

<form method="post" action="/admin/showclass"> 
<table class="table table-bordered"> 
    <label>Show Table By:</label> 
    <select> 
    <option value="all">All</option> 
    <option value="recent">Recent</option> 
    <option value="opel">Opel</option> 
    <option value="audi">Audi</option> 
    </select> 
    <tr> 
     <th>Class Name</th> 
     <th>Class Time</th> 
     <th>Duration</th> 
     <th>Instructor</th> 
     <th>Maximum Students</th> 
     <th>Brief Description</th> 
     <th></th> 
    </tr> 
    <tr> 
     <td>Data</td> 
     <td>Data</td> 
     <td>Data</td> 
     <td>Data</td> 
     <td>Data</td> 
     <td>Data</td> 
     <td><a href="editclass">Edit</a>/Delete</td> 
    </tr> 
<button type="submit" class="btn btn-default">Submit</button> 
</table> 
</form> 

<%- include('includes/footer') %> 
+0

你要通過你的res.send命令,隨後引起錯誤res.redner命令。您只能回覆一次請求。 另外,我建議你閱讀有關EJS模板化[鏈接](http://ejs.co/) – ChicoDelaBarrio

+0

因爲調用「res.send()」和「res.render()」的順序,你的錯誤。如果你想將數據發送到您的EJS你可以傳遞參數像res.render對象(「showclass」,{參數1:「測試」}) – efkan

+0

謝謝,我會讀了鏈接和更新我的代碼。 –

回答

1

res.sendres.render都做同樣的事情,他們發回響應給用戶,你不能同時使用它們,除去res.send(doc)和通你的數據爲render方法。

router.get('/showclass', function(req, res) { 
    res.render('showclass'); 
}); 
router.post('/showclass', function(req, res) { 
    var selectValue = req.body.table; 
    if(selectValue == 'all') { 
     console.log('All is selected'); 
     db.classes.find().forEach(function(err, doc) { 
      if(err) { 
       res.send(err); 
      } else { 
       res.render('showclass', { doc: doc }); 
      } 
     }); 
    } 
}); 

看看express docs

+0

因此,在我發送文檔後,在html文件中,我可以使用doc.whatevervalue? –

+0

@NasimAhmed是的,你可以 – Farnabaz