问题
I'm building a Node.js application with express. I use express-session for sessions. The data I store in a session is available in IE, Chrome and Firefox. But in Safari the session is empty all the time. So when I do console.log(req.session)
it prints:
Session {
cookie: {
path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
secure: true
},
userHasCheckCorrect: true
}
This are my settings in server.js
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
secure: true,
httpOnly: true
}
}));
It's a server with SSL certificate so it's a HTTPS domain. With HTTP it seems to work fine in Safari. What am I doing wrong here? Is there a setting I'm missing? I've looked on many places but couldn't find the answer yet. And why does it work in all browsers expect for Safari?
回答1:
With Safari it is required to pass in credentials: 'include' in request header, otherwise it doesn't send cookies.
You might also want to set a global response header after your set your session middleware by something like this:
app.use(function(req, res, next) {
res.set('credentials', 'include');
res.set('Access-Control-Allow-Credentials', true);
res.set('Access-Control-Allow-Origin', req.headers.origin);
res.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
next();
});
来源:https://stackoverflow.com/questions/50717702/express-session-is-empty-in-safari