javascript - Nodejs提交表单后出错

标签 javascript node.js mongodb

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/

相关文章:

javascript - AngularJS 指令需要监视两个属性

javascript - 写返回的重要性

javascript - 在multer上传文件之前如何获取正文?

javascript - 找不到模块 'node'

ruby-on-rails - rails 3 : Call back for when a certain object is pulled from the database (Mongo Mapper)

mongodb - Pymongo:为集合更新设置 w 会覆盖默认的写关注选项

javascript - Nock 拦截器链接,第二个模拟被忽略

javascript - 创建包含集合中所有 Azure 团队项目的下拉列表

node.js - 如何处理nodejs中的xhr blob post

python - 如何从纬度转换为邮政编码或州以生成等值线 map