检查会话时无法读取未定义的属性“名称”

时间:2018-08-25 18:07:16

标签: node.js express cookies session-cookies express-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");
    }
  );
});

我该如何解决?

1 个答案:

答案 0 :(得分:1)

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

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