我使用快速会话节点模块来获取安全会话cookie。
// Secure session cookie that ensures certain requests require an active session
app.use(expressSession({
secret: "wouldn'tyouliketoknow",
cookie: {
maxAge: new Date(Date.now() + 3600), // 1 hour
httpOnly: true,
secure: true, // Requires https connection
},
// Stores sessions in Mongo DB
store: new MongoStore({
host: mongo,
port: 27017,
db: 'iod',
collection: 'sessions'
}),
// Gets rid of the annoying deprecated messages
resave: false,
saveUninitialized: false
}));
无论请求是什么,这都会创建一个安全的会话cookie。我只想在用户成功登录时创建一个会话,例如像这样的请求:
app.get("/authenticate/:username/:password", function(req, res, next) {
...
});
基本上我只想在get处理程序中成功满足条件时创建cookie。
我该怎么做呢?理解
答案 0 :(得分:2)
因此,express会按照您将其添加到app
的顺序运行中间件。因此,实现目标的正常策略是确保定义:
但是特别回答你的问题,即使这种方法最终不可行,你只需将会话从全局中间件转换为仅添加到该路径的中间件:
var sessionMW = expressSession({
secret: "wouldn'tyouliketoknow",
cookie: {
maxAge: new Date(Date.now() + 3600), // 1 hour
httpOnly: true,
secure: true, // Requires https connection
},
// Stores sessions in Mongo DB
store: new MongoStore({
host: mongo,
port: 27017,
db: 'iod',
collection: 'sessions'
}),
// Gets rid of the annoying deprecated messages
resave: false,
saveUninitialized: false
});
app.get("/authenticate/:username/:password", sessionMW, function(req, res, next) {
...
});