无法读取 Nodejs 中未定义的属性

Cannot read properties of undefined in Nodejs

我正在尝试在 nodejs、express 和 mysql 中使用 MVC 在没有 JWT 的情况下进行示例注册,所以当我 运行 我的代码出现错误时:

TypeError:无法在 exports.register

读取未定义的属性(读取 'firstName')

这是我的代码:

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 });
          });
        };

在您的 exports.register 中,如果主体未定义,您 .send()。这并不意味着其余代码不会被执行。

替换:

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

来自

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

在我看来,req.body 似乎是未定义的。我认为您可能需要像 body-parser 这样的东西,从版本 4 开始,它已被添加到 Express 的核心中。

尝试将此中间件添加到您的入口点:app.use(express.json());

在此处查看更多信息:http://expressjs.com/en/api.html#express.json