4
我为我的expressjs项目使用Ejs模板引擎,尽管将我的对象传递给我的视图blog.ejs文件,但我在我的ejs文件中收到blogpost not defined
错误。我的<% blogpost.forEach(function(blogpost) { %>
行发生错误。我认为这与传递对象及其属性有什么关系,但我遵循指导原则,看起来是正确的。传递变量与EJS模板
routes.js:
//blog
router.route('/blog')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // set the blog content
blogpost.date = req.body.date; // set the date of the post
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog created.' });
});
}) // END POST method
// START GET method
.get(function(req, res) {
Blogpost.find(function(err, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // set the author name
blogpost.content = req.body.content; // update the blog content
blogpost.date = req.body.date; // set the date of the post
res.render('pages/blog', {
title: blogpost.title,
author: blogpost.author,
content: blogpost.content,
date: blogpost.date
});
});
}); // END GET method
blog.ejs:
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="grid">
<div class="col-1-1">
<div class="body-content">
<% blogpost.forEach(function(blogpost) { %>
<h1><%= blogpost.title %></h1>
<% }); %>
</div>
</div>
</div>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
谢谢你的答案,它解决了我的错误信息,但你的解决方案在我加载页面时在h1标记中呈现'undefined'结果。这可能是因为我的数据库中有多个条目,并且它不能一次拉出所有条目?或者更多是因为'[blogpost]'数组没有提取数据? – cphill 2014-09-01 01:18:50
我更新了解决方案。我猜是什么让我失望了,是因为你已经将'POST'代码复制并粘贴到'GET'路由处理程序('blogpost.title = ...'种类的行)。 – mscdex 2014-09-01 01:31:42