Ad

Cannot Read Property "name" Of Undefined While Checking Session

So I'm new to express and I made some kind of program that registers the session only if you logged in successfully and then uses it in other routes to apply different stuff depending if the session exists or not.

However, the problem is that it gives me an error of

Cannot read property "name" of undefined

Why? I even logged in successfully so the session should exist, right?

This is the code:

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

How I fix it?

Ad

Answer

You have to check whole path if it exists not just last properties. If user is not an object even typeof will fail because it tries to access the property of 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");
});
Ad
source: stackoverflow.com
Ad