问题
I am trying to save a session variable for a user when they login. This works on the computer, but when I try it on an iPad using Safari or Chrome it doesn't save.
Here is where I set up my session:
app.set('trust proxy', 1)
app.use(session({
secret: crypto.randomBytes(20).toString('hex'),
resave: false,
duration: 60 * 60 * 1000,
activeDuration: 10 * 60 * 1000,
saveUninitialized: false,
cookieName: 'session',
cookie: { secure: true }
}))
I use this route to set up the user:
.get('/checkLogin', (req,res) => {
const loginCred = req.query;
db.any('SELECT * FROM users WHERE user_name = $1 AND password = $2 LIMIT 1', [loginCred[0], loginCred[1]])
.then(function (user) {
req.session.user = user;
req.session.save();
res.end(JSON.stringify(user));
})
.catch(function (err) {
throw err;
})
})
When I console log this, it is getting set properly.
Then when I call the session on the return it is not there. I've tried to add the save and that still didn't work. I also added maxage
to the session variable to keep it alive for 3 days and it still didn't work.
回答1:
You have your cookie {secure: true} which requires a HTTPS connection for the browser to send the session cookie back with the request. However recommended make sure it fits your testing environment, make sure you're using HTTPS on both devices
https://www.npmjs.com/package/express-session#cookiesecure
Also with development or production mode and restarting express after making changes your secret changes after every restart (from using a function [crypto.randomBytes(20).toString('hex')] instead of a static key) causing a client's session ID to be invalid after restart; which shouldn't matter anyway cause you have no persistent sessions setup so any restart will wipe all sessions. If you need persistent sessions check into using memcached, database, or file instead of process memory
https://www.npmjs.com/package/express-session#store
回答2:
Try putting resave: true
. If it works you might want to change value of saveUninitialized
来源:https://stackoverflow.com/questions/51888214/express-session-not-saving-for-ipad