【问题标题】:Not receiving any cookie in response using express-session使用快速会话未收到任何 cookie 作为响应
【发布时间】:2020-07-25 14:12:28
【问题描述】:

我已经开始使用 express-session。但我没有收到任何 cookie 作为回应。这是我的代码:

app.use(session({
    secret: 'jdfgghuheghgjbfhfguhrughhdjdjhjghj',
    saveUninitialized: false,
    resave: false
}))

app.post('/api/login', async (req, res) => {
    const {email, password} = req.body
    //console.log(req.body)
    console.log(email, password)
    const resp = await User.findOne({email,password})
    // console.log(resp)

    if(!resp) {
        // console.log("incorrect details")
        res.json({
            success: false,
            message: "Incorrect details"
        })
        // user login is incorrect 
    } else {
        res.json({
            success: true 
        })
        req.session.user = email
        req.session.save()
        console.log("logging you in")
        //make a session and set user to logged in.
    }
 
})

试图让用户来到这里:

app.get('/api/data', (req, res) => {
    console.log(req.session)
    res.send('User is =>' + req.session.user)
})
 

我应该在网络选项卡的响应标头中获得一个 set-cookie。谁能告诉我我错过了什么?

【问题讨论】:

    标签: express-session


    【解决方案1】:

    您可以在 Chrome DevTools 的以下位置找到 Cookie:

    应用程序 > 存储 > Cookies > 快递服务器的 URL

    参考:Where is the express-session cookie hidden?

    除非您将 httpOnly 设置为 false,否则您的 cookie 将无法通过 Javascript 访问。虽然我不推荐它,因为它是为 cookie 添加的安全措施

    【讨论】:

      【解决方案2】:

      你如何称呼你的端点?根据 http 请求,您可能需要使用credentials 发送。

      当您通过 Postman 发送或您的前端在不同的端口上运行时就是这种情况。

      fetch('https://example.com', {
        credentials: 'include'
      });
      

      这是在服务器端对我有用的一种方式:也许这对你也有帮助。

      const sessionStore = new MongoStore({ mongooseConnection: connection });
      const sessionMiddleware = session({
        secret: secret,
        saveUninitialized: false,
        resave: true,
        rolling: true,
        cookie: {
          maxAge: 1000 * 60 * 60 /* 60min */,
          httpOnly: false,
        },
        store: sessionStore,
      });
      
      app.use(sessionMiddleware);
      

      【讨论】:

        猜你喜欢
        • 2020-11-11
        • 1970-01-01
        • 2016-08-08
        • 2017-10-17
        • 2017-03-30
        • 2017-01-07
        • 2014-04-16
        • 2016-11-30
        • 1970-01-01
        相关资源
        最近更新 更多