gpt4 book ai didi

node.js - 类型错误 : Cannot read property 'crud_name' of undefined

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:26 24 4
gpt4 key购买 nike

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

TypeError: Cannot read property 'crud_name' of undefined at insertRecord (D:\nodejs\node_web\controllers\crudController.js:18:28) at router.post (D:\nodejs\node_web\controllers\crudController.js:12:6)

Controller :

  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>

最佳答案

首次运行

npm 我的主体解析器

将这些添加到您的 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

在这里阅读有关 body-parser 的更多信息 https://www.npmjs.com/package/body-parser

关于node.js - 类型错误 : Cannot read property 'crud_name' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57708554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com