Home > Enterprise >  Cannot read properties of undefined in Nodejs
Cannot read properties of undefined in Nodejs

Time:11-10

I'm trying to do a sample register without JWT using MVC in nodejs, express and mysql so when I run my code and I have an error :

TypeError: Cannot read properties of undefined (reading 'firstName') at exports.register

here is my code :

AuthController

const AuthModel = require('../models/Auth')

// Create and Save a new User
exports.register = (req, res) => {
  // Validate request
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
  }

  // Create user
  const user = new AuthModel({
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    email: req.body.email,
    password: req.body.password
  });

  // Save user in the database
  AuthModel.createUser(user, (err, data) => {
    if (err)
      res.status(500).send({
        message:
          err.message || "Some error occurred while registring."
      });
    else res.send(data);
  });
};

AuthModel

const AuthModel = function(table){
   
    this.firstName = table.firstName;
    this.lastName = table.lastName;
    this.email = table.email;
    this.password = table.password;

}

AuthModel.createUser = ( newUser, result ) =>{

        db.query("INSERT INTO users SET ?", newUser, (err, res) => {
            if (err) {
              console.log("error: ", err);
              result(err, null);
              return;
            }
        
            console.log("User are registed: ", { id: res.insertId, ...newUser });
            result(null, { id: res.insertId, ...newUser });
          });
        };

CodePudding user response:

It seems to me as if the req.body is undefined. I think you might need something like body-parser, which has been added into the core of Express starting with version 4.

Try adding this middleware to your entrypoint: app.use(express.json());

See more here: http://expressjs.com/en/api.html#express.json

CodePudding user response:

In your exports.register, you .send() if the body is undefined. That doesn't mean the rest of the code won't be executed.

Replace:

res.status(400).send({
   message: "Content can not be empty!"
});

by

return res.status(400).send({
   message: "Content can not be empty!"
});
  • Related