简体   繁体   中英

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. I do get a TypeError: Cannot read property 'name' of undefined error. 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 . Adding the following middleware before your handlers should fix the problem:

const bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded({ extended: false })) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM