我有一个表单页面,它接受一些输入,将数据存储在mongo中,并将数据返回到表单下面的视图。但是,当用户在表单上提交新数据时,玉视图会崩溃并显示以下错误:
TypeError: /Users/rhysedwards/Downloads/insightful/food/views/index.jade:29
27| label
28| input.btn.btn-default(name='submit', type='submit', onsubmit="this.submit(); this.reset(); return false;")
> 29| each Entry, i in entries
30| div.title= Entry.title
31| div.url= Entry.url
32| div.selectedDate= Entry.selectedDate
Cannot read property 'length' of undefined
预期的行为是,当用户通过表单提交新数据时,它会显示在表单下方。为什么Entry
在提交时未定义,但数据仍然在提交之前显示?
路由器
router.get('/', function(req, res, next){
Entry.find({}, function (err, entries) {
res.render('index', {
"entries": entries
});
});
});
玉
block content
.container
h1 London Plans
form(method='post' action='post', class='plans', id='plans')
.form-group
label Do you have a link?
input.form-control(name='search', id='search' type='url', required='required')
h2#title
.form-group
label What looks cool?
input.form-control(name='title', type='text', required='required' class='title')
.form-group
label When is it?
label
input(type='checkbox' name='week' value='week')
span This week
label
input(type='checkbox' name='month' value='month')
span This Month
label
input(type='checkbox' id='date')
span Date
label
input(type='textbox' class='datepicker' name='date' value='')
label
input.btn.btn-default(name='submit', type='submit', onsubmit="this.submit(); this.reset(); return false;")
each Entry, i in entries
div.title= Entry.title
div.url= Entry.url
div.selectedDate= Entry.selectedDate
发布功能
router.post('/post', function(req, res, next) {
var url = req.body.search;
var title = req.body.title;
var week = req.body.week;
var month = req.body.month;
var date = req.body.date;
console.log(url + ' ' + title + ' ' + week + ' ' + month + ' ' + date);
//FIND WHICH DATE WAS SELECTED BY USER AND ASSIGN THAT TO selectedDate
if (typeof week != 'undefined' ){
var selectedDate = 'week';
} else if (typeof month != 'undefined') {
var selectedDate = 'month';
} else {
var selectedDate = date;
};
//CREATE NEW OBJECT
var data = new Entry ({
url: url,
title: title,
selectedDate: selectedDate
})
//STORE NEW OBJECT TO THE DB
Entry.createEntry(data, function(err, entry){
if (err) throw err;
console.log(entry);
})
//RENDER THE HOMEPAGE TO CLEAR THE FORM
res.render('index');
return false;
});
答案 0 :(得分:2)
重新提交时未定义条目的原因是因为在router.post
处理程序中,您没有为Jade模板提供该变量的值。
以下是router.post
处理程序中导致此问题的代码:
res.render('index'); // telling the page to render without variables
现在,将其与router.get
处理程序中的成功代码进行比较:
res.render('index', {
"entries": entries // here is where you assign variables for Jade
});
正如您所看到的,在router.get
处理程序中,您为Jade模板引擎提供了带有"entries"
的{{1}}变量的值,这是调用返回的值你对mongodb做了。
有关详细信息,请查看the express docs for res.render()
。以下是有关摘要的摘录:
entries
呈现视图并将呈现的HTML字符串发送到客户端。 可选参数:
res.render(view [, locals] [, callback])
,一个对象,其属性定义了局部变量 图。强>
从locals
参数的定义中,您可以看到出错的地方!快乐的编码:)