req.session 在快速会话中不持久

req.session in express-session not persisting

我有以下代码:

var express = require('express');
var cookieParser = require('cookie-parser');
var http = require('http')
var app = express();
app.use(cookieParser());
var session = require('express-session');
app.use(session({
    resave: false,
    saveUninitialized: true,
    secret: 'sdlfjljrowuroweu',
    cookie: { secure: true }
}));

app.get('/test', test);
function test(req, res) {
    var sess = req.session;
    console.log('before', sess);
    if (sess.views) {
        sess.views++
        req.session.save();
        res.setHeader('Content-Type', 'text/html')
        res.write('<p>views: ' + sess.views + '</p>')
        res.write('<p>expires in: ' + (sess.cookie.maxAge / 1000) + 's</p>')
        res.end();
    } else {
        sess.views = 1;
        req.session.save();
        res.end('welcome to the session demo. refresh!')
    }
    console.log('after', sess);
    return;
}

var server = http.createServer(app);
server.listen(8181);

重新加载页面后,我一直收到查看次数为 0 的消息。

查看控制台,每次都是这样输出:

before { cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: true } }
after { cookie: 
   { path: '/',
     _expires: null,
     originalMaxAge: null,
     httpOnly: true,
     secure: true },
  views: 1 }

所以它似乎根本没有节省

cookie: { secure: true }更改为cookie: { secure: false }

使用 secure 标志意味着 cookie 将仅在 Https 上设置。