【问题标题】:Can't not set cookie in express-session using node.js无法使用 node.js 在快速会话中设置 cookie
【发布时间】:2021-10-22 01:05:08
【问题描述】:

我尝试查看我的 cookie 是否有效,所以这是我的代码

    const RedisStore = connectRedis(session)
    const redisClient = redis.createClient()
    app.use(
        session({
            //name: 'qid',
            store: new RedisStore({  //ttl: how long it should last
                client: redisClient, 
                //disableTTL :true, //make sure session last forever
                //disableTouch: true, // make sure it does'nt have to update the last time it's ttl
            }),
            cookie:{
                maxAge: 1000*60*60*24*365*10, //10 years
                path: "/"
                //httpOnly:true, //javascript front end can't access
                //sameSite:'none', // csrf
                //secure:false
                //secure: __prod__ //cookie only works in https
            },
            saveUninitialized:true, //automatically create a empty session on default
            secret: 'some secret', //env
            resave: false,
        }) 
    )
    app.listen(4000,()=>{
        console.log('server stared on localhost:4000')
    })
    app.get('/products', (req,res,next) => {
        console.log(req.session);
        if(!req.session.userId){
            req.session.userId = 1
        }else{
            req.session.userId = req.session.userId +1
        }
        console.log(req.session.userId) //test if work
        res.send("hello")
    })

所以事情是这样的,当我连接到 localhost:4000/products 时,在 cookie 会话中,我只能看到这些

但是当我在 vscode 控制台上打印结果时,我可以看到数字在增长,如下所示,所以我确实有一个会话,只是没有显示在浏览器上,谁能告诉我这是为什么?

server stared on localhost:4000
Session {
  cookie: {
    path: '/',
    _expires: 2031-08-18T12:59:30.827Z,
    originalMaxAge: 315360000000,
    httpOnly: true
  },
  userId: 10
}
11
Session {
  cookie: {
    path: '/',
    _expires: 2031-08-18T13:00:37.257Z,
    originalMaxAge: 315360000000,
    httpOnly: true
  },
  userId: 11
}
12

【问题讨论】:

    标签: node.js session cookies express-session


    【解决方案1】:

    所以经过大量测试后我得到了一个解决方案,所以如果你只将你的 cookie 设置为相同站点:“none”而没有安全选项,这就像我的情况,但如果你想打开安全选项你端点必须是 https,所以我认为这不是答案,您可以更改为 lax 或其他选项,它会在您的 localhost 中正常运行,

    在本地主机中工作

    • 松懈
    • (不要设置同一个站点)

    但是由于安全策略https://www.chromium.org/updates/same-site,如果不设置 same-site:"none" 安全,您不能不将 cookie 传递到某些特定网站(在我的情况下,我想在我的 graphql apollo 工作室中测试 cookie),所以我使用 mkcert 在我的本地主机中使用 https https://web.dev/how-to-use-local-https/ ,一切正常,

    工作

    • 同一站点:无
    • 安全:真实
    • https:你的端点

    【讨论】:

      猜你喜欢
      • 2020-10-20
      • 2020-01-19
      • 2019-12-29
      • 2020-11-11
      • 2016-08-08
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      相关资源
      最近更新 更多