Answer the question
In order to leave comments, you need to log in
How to work with sessions in node+express?
All the best!
Decided to try to play a little with authorization, with the help of sessions.
I ran into a problem when the cookie session expires: {maxAge: new Date(Date.now() + (60 * 1000 * 1))} re-visiting something in req.session fails :(
Here is a piece of my code:
let session = require('express-session');
app.use(session({
secret: 'aaa2C44-4D44-WppQ38Siuyiuy',
cookie: {maxAge: new Date(Date.now() + (60 * 1000 * 1))},
resave: true,
saveUninitialized: true
}));
let checkSignIn = (req, res, next) => {
if (req.session.user) { // после истичения сессии req.session.user всегда undefined,
//несмотря на то что в
//логине я повторно задаю это
// свойство req.session.user = user['_id']
next();
} else {
res.redirect("/login");
}
}
app.post("/login", (req, res) => {
if(req.body.usr == user && req.body.pwd == password)
req.session.user = user['_id']
res.redirect("/manage");
} else {
console.log('Could not find user')
res.render('login')
}
})
})
app.get("/manage", checkSignIn, (req, res) => {
res.render('index')
})
Answer the question
In order to leave comments, you need to log in
Replaced cookie.maxAge from date to time and everything is fine :)
i.e. from new Date(Date.now() + (60 * 1000 * 1)) to 90000
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question