在快速会话中保存数据

时间:2018-10-09 10:05:16

标签: node.js express session

我想在Express-Session上登录后保存我的令牌。我的要求是:

app.prepare().then(() => {
  express()
    .use(session({
        secret: 'this-is-a-secret-token',
        resave: false,
        saveUninitialized: true,
        cookie: { maxAge: 60000 }
      }))
    .get(server.login_check, async (req, res) => {
      console.log(req.session.token);
      console.log('------------');

      if (!req.session.token) {
        try {
          const request = await loginThroughApi();

          if (request) {
            console.log(request);
            req.session.token = request.token;
            return request.token;
          }
        } catch (error) {
          console.log('Error:', error);
        }
      } else {
        console.log(req.session.token);
      }
    })

req.session.token始终是未定义的,我不太明白为什么^^

2 个答案:

答案 0 :(得分:0)

我不确定在共享代码之前如何激发您的兴趣,但是我认为您应该app.use(session(...))而不是express.use(session(...))。同样,这取决于您如何设置此变量。也许您可以遵循初始化指南here

答案 1 :(得分:0)

您需要这样的呼叫

req.session.token = request.token;
req.session.save();