Cannot read property 'email' of undefined
我是node和mongo的新手,我正在努力学习它们。这是我的简单应用,我想使用 Jade
保存表单数据。
JADE
form.form-horizontal(method="post", id="loginForm" action="/new")
label Email
input.span3(id="email", type="text", name="email", placeholder="Enter your Email")
label Name
input.span3(id="name", type="text", name="name", placeholder="Your Name")
label Age
input.span3(id="age", type="number", name="age", placeholder="Your Age")
div.login
input.btn.warning(type="submit", value="Log In")
app.js
mongoose.connect("mongodb://localhost/mean");
var Schema = new mongoose.Schema(
{
_id :"string",
name:"string",
age :"number"
}
);
var user = mongoose.model("emp", Schema);
app.get('/', routes.index);
app.get('/users', users.list);
app.post("/new", function(res, req){
new user({
_id : req.body.email,
name: req.body.name,
age : req.body.age
}).save(function(err, doc){
if(err){
res.json(err);
}else{
res.send("Data inserted successfully !");
}
});
});
提交后我收到此错误:
Cannot read property 'email' of undefined
答案 0 :(得分:2)
你在这里做了一个基本的错误
app.post("/new", function(res, req){
第一个参数(res
)实际上是request
对象,第二个参数(req
)是response
对象。此处email
request
对象中存在res
。将代码更改为
new user({
_id : res.body.email,
name: res.body.name,
age : res.body.age
})
或者我建议简单地交换这样的参数,并且每件事都应该有效:
app.post("/new", function(req, res){... //See I swapped the variable, now it should work.