0

So I'm new to express(and backend as whole) and to be fair I don't know exactly how to use sessions(I started by using cookies first but then I heared that sessions are better to maintain user's state) so I installed express-session and did like this post did:

https://stackoverflow.com/a/37608202/5737650

Where I saved the session in a variable(sess) and then I used to get the informations out but the problem is that it seems like sess is only the cookie object and not the other informations I need to save user's inputs in which gave me this error:

Cannot set property "name" of undefined

This is my code which is its job is to register the user, save the data to database then when it goes to login page, it checks if his inputs exist in database or not, if not then it will give me a console.log, if exist then it will save the data to the session so that I can maintain its state later but it gives me the above error when I enter the correct inputs:

// 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
    },
    user: {
      name: "",
      password: "",
      status: ""
    }
  })
);
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) {
  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;
      console.log("Query got excuted successfully!");
    }
  );
});

app.post("/Login", urlencodedParser, (req, res) => {
  let sess = req.session;
  console.log(sess);
  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 {
        console.log("Logined successfully!");
        sess.user.name = req.body.Username;
        sess.user.password = req.body.Password;
        sess.user.status = "online";
      }
      res.render("Login");
    }
  );
});

How I fix this and get the result I want(maintain its state as logged all throught the website)?

Boy pro
  • 452
  • 4
  • 19

1 Answers1

1

There are a couple of mistakes in the code.

  1. Initially, the session object would not have user object. Thus sess.user would be undefined. So the first error Cannot set property "name" of undefined makes sense. You might want to initialize sess.user to empty object first.

  2. With the POST the request, you need to call the .save() on the req.session to save it. Read more about it here

Here is the code I tried on my machine:

app.post("/Login", (req, res) => {
    let sess = req.session;
    res.send(sess);
    sess.user = {};
    sess.user.name = req.body.Username;
    sess.user.password = req.body.Password;
    sess.user.status = "online";
    req.session.save();
});

You could do something like this:

app.post("/Login", urlencodedParser, (req, res) => {
    let sess = req.session;
    console.log(sess);
    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 {
                console.log("Logined successfully!");
                sess.user = {
                    name: req.body.Username,
                    password: req.body.Password,
                    status: "online"
                };
            }
            req.session.save();
            res.render("Login");
        }
    );
});
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33
  • I don't understand. Why I should put res.send(sess), why sess.user = {} why not just making it directly {} why req.session.save()? Can you explain these please more? I'm new to express and session thing. – Boy pro Aug 25 '18 at 15:11
  • 1
    Umm No. You do not need `res.send(sess)`. I did that so that I can easily see the session variables in the response. About `req.session.save()`, I recommend going through the link I posted and then ask exactly which point you do not understand – Anand Undavia Aug 25 '18 at 15:18
  • 1
    I am not clear what are you asking by your this line => why sess.user = {} why not just making it directly {} – Anand Undavia Aug 25 '18 at 15:18
  • @Anad Undavia I mean what's the difference between session {user: //code} and sess.something = {//code}}? Isn't sess is the whole session object or I'm missing something here? – Boy pro Aug 25 '18 at 15:24
  • 1
    Yes, `sess` is the whole session object. And it is completely up to you to either user `sess.user.name = 'xxx'` or `sess.name = 'xxx'` ( you, however, can not do `sess = 'xxx'` ) – Anand Undavia Aug 25 '18 at 15:33
  • You didn't get what I was trying to say but fine, thank you a lot for the explaining! it was really useful! @Anand Undavia – Boy pro Aug 25 '18 at 15:39
  • 1
    Thanks :) If you want more help, let's chat here https://chat.stackoverflow.com/rooms/17/javascript – Anand Undavia Aug 25 '18 at 15:39
  • There is a problem, your way works perfectly but when I want to check if username/password exists in req.session in other routes, it shows me an error that req.session.user.name doesn't exist. What I do? – Boy pro Aug 25 '18 at 17:43
  • 1
    First, check if the `req.session.user` exists or not, if it does, check if `req.session.user.name` exists\ or not. – Anand Undavia Aug 25 '18 at 19:34