2017-12-27 416 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