可以使用Express中间件来控制Session的创建。以下是一种可能的解决方案:
const express = require('express');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const app = express();
app.use(session({
secret: 'mysecretkey',
saveUninitialized: false,
resave: false,
store: new MongoStore({
url: 'mongodb://localhost/myapp',
ttl: 14 * 24 * 60 * 60 // session will expire after 2 weeks
})
}));
app.use((req, res, next) => {
if (!req.session.firstSession) {
req.session.firstSession = true;
return next();
}
next('route');
});
app.get('/', (req, res) => {
res.send('This is the second session');
});
app.get('/', (req, res) => {
res.send('This is the first session');
});
这段代码中,我们在使用Express的Session中间件时指定了一个store
选项,用来将Session数据存储到MongoDB中。此外,我们添加了一个自定义中间件,当第一次请求到来时,它会创建一个新的Session,而后续的请求会跳过这个中间件,直接传递第二个Session给路由器。为了演示其效果,我们添加了两个路由处理程序,分别用于显示第一个和第二个Session中的内容。