Express session is empty in Safari

南楼画角 提交于 2020-06-27 11:03:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!