The following code handles post requests to my application's login page.
If the login credentials are correct it sets the is_logged_in session variable to true as well as the user_id to the user id fetched from a database.
In the query that gets the credentials, if everything passes I have a second query that gets the student id. For some odd reason when I try to set the req.session.student_id variable and log the session object I don't see it, it only sets the is_logged_in and user_id variables that are set from outside the second query function.
router.post('/login', (req, res) => {
con.query("SELECT id, username, password FROM authorizedusers;",
(err, result) => {
if(err) throw err;
for(var i = 0; i < result.length; i++) {
if(req.body.username === result[i].username
&& req.body.password === result[i].password){
con.query(`SELECT id FROM students WHERE user_id =
${result[i].id};`, (err, result) => {
if(err) throw err;
req.session.student_id = result[0].id;
});
req.session.is_logged_in = true;
req.session.user_id = result[i].id;
return res.redirect('/');
}
}
return res.render('login', {
msg: "Error! Invalid Credentials!"
});
});
});
This is what I get when I log the session object.
Session {
cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true },
is_logged_in: true,
user_id: 3
}
However, if I try to set the student_id in the same scope as the other ones, as follows:
router.post('/login', (req, res) => {
con.query("SELECT id, username, password FROM authorizedusers;",
(err, result) => {
if(err) throw err;
for(var i = 0; i < result.length; i++) {
if(req.body.username === result[i].username
&& req.body.password === result[i].password){
con.query(`SELECT id FROM students WHERE user_id =
${result[i].id};`, (err, result) => {
if(err) throw err;
});
req.session.student_id = "test";
req.session.is_logged_in = true;
req.session.user_id = result[i].id;
return res.redirect('/');
}
}
return res.render('login', {
msg: "Error! Invalid Credentials!"
});
});
});
It does work, and this is what I get after when I log the session object.
Session {
cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true },
student_id: 'test',
is_logged_in: true,
user_id: 3
}
Why does this happen, and how can I fix it?
update
jfriend00 Answered my question, and said that I could solve my issue by using the mysql2 module instead of the mysql module.
I would like to use the mysql module though. So I would appriceate if somebody could answer how solve this issue while using the mysql module.