TypeError:无法读取未定义的属性“ crud_name”

时间:2019-08-29 10:49:33

标签: node.js mongodb node-modules

您好,我正在尝试使用nodejs将数据保存到mongodb中,但是它说:

  

TypeError:无法读取未定义的属性“ crud_name”       在insertRecord(D:\ nodejs \ node_web \ controllers \ crudController.js:18:28)       在router.post(D:\ nodejs \ node_web \ controllers \ crudController.js:12:6)

控制器:

  router.get('/crud',(req, res) => {
res.render("crud", {crud : new Crud(), newCrud : true});
});

router.post('/', (req, res) => {
    insertRecord(req, res);
});

function insertRecord(req, res) {
console.log(req.body);
var crud = new Crud();
crud.crud_name = req.body.crud_name;
crud.crud_email = req.body.crud_email;
crud.crud_mobile = req.body.crud_mobile;
// Save methods
crud.save((err, doc) => {
    if (!err)
      res.redirect('crud');
    else {
        console.log('Error during record insertions : ' + err);
    }
});
}

模式:

   var crudSchema = new mongoose.Schema({

crud_name: {
    type: String
},

crud_email: {
    type: String
},

crud_mobile: {
    type: String
}

 });

  mongoose.model('Crud', crudSchema );

表格:

  <form method="POST" action="/crud">
  <div class="form-group">
   <label for="inputAddress">Name</label>
    <input type="text" name="crud_name" class="form-control" id="inputAddress" placeholder="Enter your name">
  </div>
  <div class="form-group">
    <label for="inputAddress">Email</label>
    <input type="email" name="crud_email" class="form-control" id="inputAddress" placeholder="Enter your email">
  </div>
  <div class="form-group">
    <label for="inputAddress">Mobile</label>
    <input type="number" name="crud_mobile" class="form-control" id="inputAddress" placeholder="Enter your mobile">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
 </form>

1 个答案:

答案 0 :(得分:0)

首次运行

npm i body-parser

将它们添加到您的app.js / main.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');

//This will serve parsing for the whole application.
app.use(bodyParser.json());

//Rest of the code 

在此处详细了解人体分析器 https://www.npmjs.com/package/body-parser