[英]TypeError: Cannot read property 'name' of undefined. I cannot find the reason why I get this error. I am using mysql, nodejs and ejs as view engine
I am Trying to Add new users into a MySql database in nodejs and EJS as a view engine.我正在尝试将新用户添加到 nodejs 和 EJS 中的 MySql 数据库中作为视图引擎。 I do get a TypeError: Cannot read property 'name' of undefined error.
我确实收到 TypeError: Cannot read property 'name' of undefined 错误。 Can somebody please assist as I cannot find the reason why I get this error.
有人可以帮忙,因为我找不到我收到此错误的原因。
My Routing const express = require("express"); var router = express.Router(); const mysql = require("mysql"); const mysqlConnection = require("../connection"); router.get("/", function (req, res) { let mysql = "SELECT * FROM user_index.clients"; let query = mysqlConnection.query(mysql, function (err, rows) { if (err) { throw err; } else { res.render("users", { title: "Mysql with EJS", users: rows, }); } }); }); router.get("/add", function (req, res) { // res.send("My add page."); res.render("add", { title: "Mysql with EJS", }); }); router.post("/add", (req, res) => { let data = { name: req.body.name, email: req.body.email, phone_number: req.body.phone_number, }; let mysql = "INSERT INTO clients SET?"; let query = mysqlConnection.query(mysql, data, function (err, result) { if (err) { throw err; } else { res.redirect("/"); } }); }); module.exports = router;
Since you're submitting a html-form
you need a corresponding parser in order to be able to access the submitted data under req.body
.由于您提交的是
html-form
,因此您需要相应的解析器才能访问req.body
下提交的数据。 Adding the following middleware before your handlers should fix the problem:在您的处理程序之前添加以下中间件应该可以解决问题:
const bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded({ extended: false }))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.