检查会话时无法读取未定义的 属性 "name"

Cannot read property "name" of undefined while checking session

所以我是新手,我做了一些程序,只有当你成功登录时才注册会话,然后在其他路由中使用它来应用不同的东西,具体取决于会话是否存在。

然而,问题是它给我一个错误

Cannot read property "name" of undefined

为什么?我什至登录成功所以会话应该存在,对吧?

这是代码:

// Importing modules/packages
let connection = require("./Connection.js");
let bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
let express = require("express");
let app = express();
var session = require("express-session");
app.use(cookieParser());
app.use(
  session({
    secret: "1E3ESS3DSS4DS4",
    saveUninitialized: true,
    resave: false,
    cookie: {
      path: "/",
      maxAge: 1000 * 60 * 60,
      httpOnly: true
    }
  })
);
let urlencodedParser = bodyParser.urlencoded({ extended: false });

// Server and routing
app.listen(3000, function() {});
app.set("view engine", "ejs");
app.get("/Signup", (req, res) => {
  res.render("Register");
});
app.get("/", function(req, res) {
  if (
    typeof req.session.user.name == "undefined" &&
    typeof req.session.user.password == "undefined"
  ) {
    res.render("Home");
  }
  res.redirect("Login");
});
app.get("/Login", function(req, res) {
  res.render("Login");
});

// Database's Connection
connection.connect(err => {
  if (err) {
    throw "ERROR! " + err;
  }
});

// Requesting and Receiving Data from body parser
app.post("/Signup", urlencodedParser, function(req, res) {
  res.render("Register");
  connection.query(
    `insert into users (Username, User_Password, Email_Address) values ("${
      req.body.Username
    }", ${req.body.Password}, "${req.body.Email}")`,
    function(err) {
      if (err) throw "An error has happened while excuting the query " + err;
    }
  );
});

app.post("/Login", urlencodedParser, (req, res) => {
  let sess = req.session;
  connection.query(
    `SELECT Username FROM users WHERE User_Password = ? AND Username = ?`,
    [req.body.Password, req.body.Username],
    function(err, results) {
      if (results.length === 0) {
        console.log(
          "Sorry, this username/password doesn't exist in our database."
        );
      } else {
        sess.user = {
          name: req.body.Username,
          password: req.body.Password,
          online: true
        };
        req.session.save();
      }
      res.render("Login");
    }
  );
});

我该如何解决?

您必须检查整个路径是否存在,而不仅仅是最后一个属性。如果 user 不是 object,甚至 typeof 也会失败,因为它试图访问未定义的 属性。

app.get("/", function(req, res) {
  if (
    typeof req.session.user != "object" || (
    typeof req.session.user.name == "undefined" &&
    typeof req.session.user.password == "undefined")
  ) {
    res.render("Home");
  }
  res.redirect("Login");
});