[英]Getting TypeError: Cannot read property 'name' of undefined, while posting the form - node.js
我正在構建一個節點 Js 項目,並將表單的值保存到 mongoDB 數據庫中。 盡管嘗試了我找不到導致此錯誤的原因。 錯誤出現在第三行的router.post
function 處。
請通過你的編碼和調試的神奇力量指導我。 :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
Object,那么為什么'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>
看起來您沒有使用正文解析器。 沒有一個, 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
編輯:另外,請確保在路由器之前使用正文解析器中間件。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.