0

This is my code

var express = require("express");
var router = express.Router();
var db = require("../database");
router.get("/form", function (req, res, next) {
  res.render("users");
});
router.post("/create", function (req, res, next) {
  // store all the user input data
  const data = req.body;

  // insert user data into users table
  var sql = "INSERT INTO users ( `fullName`, `emailAddress`, `city`,`country`) 
  VALUES ('" + data.fullName + "', '" + data.emailAddress+ "', '" + data.city + "', 
  '" + data.country + "');";
  db.query(sql, data, function (err, data) {
    if (err) throw err;
    console.log("User dat is inserted successfully ");
  });
  res.redirect("/users/form"); // redirect to user form page after inserting the
  data;
});
module.exports = router;

I am getting error like this

TypeError: Cannot read properties of undefined (reading 'fullName')
at /home/deekshitha/Videos/nodes/nodeapp/routes/_users.js:13:100
at Layer.handle [as handle_request]
(/home/deekshitha/Videos/nodes/nodeapp/node_modules/express/lib/router/layer.js:95:5)
at next 
(/home/deekshitha/Videos/nodes/nodeapp/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/deekshitha/Videos/nodes/nodeapp/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/deekshitha/Videos/nodes/nodeapp/node_modules/express/lib/router/layer.js:95:5)
at /home/deekshitha/Videos/nodes/nodeapp/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/deekshitha/Videos/nodes/nodeapp/node_modules/express/lib/router/index.js:335:12)
at next (/home/deekshitha/Videos/nodes/nodeapp/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/home/deekshitha/Videos/nodes/nodeapp/node_modules/express/lib/router/index.js:174:3)
at router (/home/deekshitha/Videos/nodes/nodeapp/node_modules/express/lib/router/index.js:47:12)
Chance Smith
  • 1,211
  • 1
  • 15
  • 32
  • you need to use `body-parser` to read the request body. Check out [this](https://stackoverflow.com/a/49943829/6516699) answer – Naren Oct 28 '21 at 06:50
  • Does this answer your question? [How to access the request body when POSTing using Node.js and Express?](https://stackoverflow.com/questions/11625519/how-to-access-the-request-body-when-posting-using-node-js-and-express) – Naren Oct 28 '21 at 06:51

1 Answers1

0

The problem here is that the boby is undefined, hence when you are trying to access fullName field of the data you see that error.

To solve that problem you need to parse the body content first, you can do that either manually or use body-parser middleware.

Ayzrian
  • 2,279
  • 1
  • 7
  • 14