【问题标题】:Getting TypeError: Cannot read property 'name' of undefined, while posting the form - node.js获取 TypeError:在发布表单时无法读取未定义的属性“名称”-node.js
【发布时间】:2021-05-09 20:39:52
【问题描述】:

我正在构建一个节点 Js 项目,并将表单的值保存到 mongoDB 数据库。 尽管尝试了我找不到导致此错误的原因。 错误出现在第 3 行的 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>

【问题讨论】:

标签: javascript node.js forms express post


【解决方案1】:

您似乎没有使用正文解析器。没有一个,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);

Docs

【讨论】:

  • 先生,感谢您的回答。看起来我的应用程序运行正确。但是我已经在 app.js 中包含了 body-parser 和中间件,那为什么当时它不起作用;但是现在当我在路由中包含相同的代码(在 js 文件上方)时,它可以正常工作。先生,您能解释一下吗?
  • @AlexEd 我不确定。你在路由之前useing 身体解析器吗? stackoverflow.com/a/49228835
  • 是的先生,我正在使用
  • 类似这样的东西:const bodyPaser = require('body-parser'); const app = express(); const employeeRoutes = require('./routes/employees');
  • @AlexEd 我编辑了我的答案以更详细地解释我的意思。正文解析器的 app.use 调用需要在路由器的 app.use 调用之前。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 2022-01-14
  • 2022-06-22
  • 2015-10-16
  • 2021-12-28
  • 1970-01-01
  • 2020-05-15
相关资源
最近更新 更多