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
最佳答案
你在这里犯了一个基本错误
app.post("/new", function(res, req){
第一个参数(res
)实际上是request
对象,第二个(req
)是响应
> 对象。 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.
关于javascript - Nodejs提交表单后出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29983457/