获取类型错误:无法读取未定义的属性"名称",同时发布表单 - Node.js



我正在构建一个节点Js项目,我正在将表单的值保存到mongoDB数据库。尽管尝试,我找不到是什么导致这个错误。第三行router.post函数出错

请通过您编码和调试的神奇力量来指导我。: D

const express = require('express');
const router = express.Router();
const Employee = require('../models/employee');
router.get('/',(req, res) => {
res.render('index');
});
router.get('/employee/new', (req, res) => {
res.render('new');
});

router.post('/employee/new', (req, res) => {
let newEmployee = {
name : req.body.name,
designation : req.body.designation,
salary : req.body.salary
}
Employee.create(newEmployee).then(employee => {
res.redirect('/');
}).catch(err => {
console.log(err);
});
});
module.exports = router;

你可以清楚地看到我已经定义了newEmployee对象,那么为什么'name'是undefined的属性。

<div class="container mt-5 w-50">
<h2 class="mb-4">Add New Employee</h2>
<form action="/employee/new" method="POST">
<input type="text" name="name" class="form-control" placeholder="Employee Name">
<input type="text" name="designation" class="form-control" placeholder="Employee Designation">
<input type="text" name="salary" class="form-control" placeholder="Employee Salary">
<button type="submit" class="btn btn-danger btn-block mt-3">Add to Database</button>
</form>
</div>

看起来不像是在使用body解析器。没有一个,req.body将永远是未定义的,这看起来像你的问题。在你定义任何路由之前,试着把这个放进去。

const bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

编辑:此外,请确保在路由器之前使用了body解析器中间件。

const employeeRoutes = require('./routes/employees');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
// This needs to come AFTER the app.use calls for the body parser
app.use(employeeRoutes);

文档

最新更新