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)?
There are a couple of mistakes in the code.
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.
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");
}
);
});