i guys I am currently using nodejs with express session and connect session sequelize.
Currently I am trying to pass my userID from session and to be accessed at another add product page. So that the database can identify based on userID. I am getting req.session.users is not a function.
Below is my code.
Sessions login page:
const User = require('../models/user')
exports.postLoginPage = (req,res,next) =>{
User.findByPk(1)
.then(users =>{
req.session.isLoggedIn = true;
req.session.users = users;
res.redirect('/');
})
.catch(err =>{
console.log(err)
})
}
the addProduct Page
exports.postaddProductsMale = (req,res,next) =>{
const title = req.body.title;
const imageUrl = req.body.imageUrl;
const price = req.body.price;
console.log(+req.session.users)
req.session.users.createProduct({
title:title,
imageUrl:imageUrl,
price:price
})
.then(results =>{
console.log('Product created')
res.redirect('male_section');
})
.catch(err =>{
console.log(err)
})
};
this is my error :
TypeError: req.session.users.createProduct is not a function
at exports.postaddProductsMale (C:\Users\ASUS\Desktop\Hobby\projects\javascript\ecommerce clothing\maarancode\controllers\admin.js:28:23
I can get the data to the other routes using req.user not sure why req.session.users is not working.
Appreciate your feedback on this question. Thank you.
req.session must be serializable so that it can be stored between requests, see for example here. But a function like req.session.users.createProduct is not serializable, so it may not survive until the next request.
See the following example
express()
.use(session({
secret: "Se$$ion",
resave: false,
saveUninitialized: false
}))
.use("/test", function(req, res) {
if (!req.session.mybool) {
req.session.mybool = true;
req.session.myfunc = function() {};
}
res.end(typeof(req.session.mybool) + " " + typeof(req.session.myfunc));
})
.listen(80);
If you make two requests, the first response is boolean function but the second is boolean undefined.