我试图传递一个隐藏的id字段的值,并使用它从mongodb中检索记录,并在索引页上单击“阅读更多”后,将其显示在个人资料页上。index.ejs:
<% for(i=0; i<users.length; i++){%>
<div class="col-lg-3 center">
<div class="text-center">
<img class="img img-circle" src="<%= users[i].image %>" height="120px" width="120px" alt=""> <br>
<h4><b><%= users[i].fname %> <%= users[i].lname %></b></h4>
<ul class="list-inline social-buttons">
<li><a href="<%= users[i].linkedin %>"><i class="fa fa-linkedin"></i></a></li>
<li><a href="<%= users[i].gitHub %>"><i class="fa fa-github"></i></a></li>
<li><a href="#"><i class="fa fa-twitter"></i></a></li>
</ul>
<input type="hidden" name="id" value="<%= users[i]._id %>" >
<p><%=users[i].bio %>....<a href="prof">Read More</a></p>
</div>
</div><!-- col-lg-3 -->
<% } %>
这是profile.ejs:
<div class="medium-4 small-12 columns">
<h3> <%= users.fname %> <%= users.lname %></h3>
<p>Username: <%= users.username %></p>
<p>Email: <%= users.email %></p>
<p> Software Developer at <%= users.role %></p>
</div>
并表达路线,users.js。
app.get('/prof',function(req, res) {
var id=req.body.id;
var user = new User();
mongoose.model('User').findById(id,function(err, users){
console.log(users);
res.render('pages/profile',{users:users});
});
});
这给我一个错误“无法读取null的属性'用户名'。”
我想念什么?
最佳答案
您正在执行GET
操作,但尝试通过id
参数发送POST
值,该参数是使用req.body.variable_name
抓取的。
在这种情况下,您不需要隐藏字段,因为它需要POST
操作才能发送到服务器。尝试发送id
作为URL参数,例如,可以使用req.param.id
或req.query.id
进行抓取
http://example.com/api/users?id=4&token=sdfa3&geo=us
要么
http://example.com/api/users/4/sdfa3/us
如果要获取查询参数
?id=57ada56845b8466147fc35b0
,请使用req.query
URL:
// GET /prof?id=57ada56845b8466147fc35b0
标记:
<p><%=users[i].bio %>....<a href="prof?id=<%= users[i]._id %>">Read More</a></p>
路线:
app.get('/prof', function(req, res) {
var id = req.query.id; // 57ada56845b8466147fc35b0
mongoose.model('User').findById(id, function(err, user){
console.log(user);
res.render('pages/profile', { users: user });
});
});
对于其他参数用法
URL:
// GET /prof/57ada56845b8466147fc35b0
使用
req.params.id
标记:
<p><%=users[i].bio %>....<a href="prof/<%= users[i]._id %>">Read More</a></p>
路线:
app.get('/prof/:id', function(req, res) {
var id = req.params.id; //57ada56845b8466147fc35b0
mongoose.model('User').findById(id, function(err, user){
console.log(user);
res.render('pages/profile', { users: user });
});
});