首页 > 解决方案 > 使用快速会话未收到任何 cookie 作为响应

问题描述

我已经开始使用快速会话。但我没有收到任何 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

解决方案


你怎么称呼你的端点?根据 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);

推荐阅读