TypeError: Cannot read properties of undefined when sending an EJS form to Express

Viewed 98

I'm new to nodeJS, the req.body.email and req.body.password in the file signupRoutes.js do not seem to be picking up the form data on the front end of my project.

Any idea why? The specific error is "TypeError: Cannot read properties of undefined (reading 'email')".

signup.ejs:

<form action='/signup' method="post">
    <label for="email">Email:</label>
    <input type="text" id="email" name="email"><br><br>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password"><br><br>
    <input type="submit" value="Submit">
</form>

signupRoutes.js:

const express = require('express');
const router = express.Router();

const User = require('../models/userModel');

router.get('/', (req, res) => {
    res.render('./signup');
    res.end();
});

router.post('/', (req, res) => {
    const user = new User({
        email: req.body.email,
        password: req.body.password
    }); 
    user.save();
    res.redirect('/index');
});

module.exports = router;

userModel.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    }
  }, {timestamps: true})

  const User = mongoose.model('User', userSchema);
  module.exports = User;

server.js:

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const ejs = require('ejs');

const homepageRoutes = require('./routes/homepageRoutes');
const signupRoutes = require('./routes/signupRoutes');
const loginRoutes = require('./routes/loginRoutes');

const dotenv = require('dotenv');
dotenv.config();
const dbusername= process.env.DB_USERNAME;
const dbpassword= process.env.DB_PASSWORD;
dbURI = `mongodb+srv://${dbusername}:${dbpassword}@testingcluster.ix9mpsg.mongodb.net/?retryWrites=true&w=majority`;
mongoose.connect(dbURI).then((result) => app.listen(4000)).catch((err) => 
console.log(err));

app.set('view engine', 'ejs');
app.use(express.static('assets'));

app.use("/index", homepageRoutes);
app.use("/signup", signupRoutes);
app.use("/login", loginRoutes);

Thanks for your time. Side note: I am aware you need to add more security to passwords, I'm just testing posting data into mongoDB for now.

Here's one thing I tried due to a user suggestion. It was to change email: req.body.email, on signupRoutes.js to email: res.json({requestBody: req.body.email}) as well as adding app.use(express.json()); above the routes in "server.js".

It just returned a blank page with an empty object, It also did not post the data into MongoDB.

1 Answers

In server.js after this line app.use(express.static('assets')) or just before the route handlers, add the below line to parse the coming request and attached it to req.body.

Without req.body is undefined, the reason why you are getting that error. Also app.use(express.json()) doesn't parse data coming from a from.

express.urlencoded({extended: false})
Related