我正在尝试使用cookie-session在我的快递应用中存储一个值。我想在我的任何路线中访问此值。 我可以在index.js文件中完美地完成这个任务。
var app = express();
app.set("trust proxy", 1);
app.use(
cookieSession({
name: "session",
secret: "key",
httpOnly: true,
maxAge: 30 * 60 * 1000,
secure: false,
overwrite: false
})
);
app.get("/", function(req, res, next) {
// Update views
req.session.views = (req.session.views || 0) + 1;
req.session.key = "some key I set"
// print out 3 views key = some key I set
res.end(req.session.views + " views " + "key = " + req.session.key);
});
我遇到的问题是当我尝试在我的某个路线中设置或获取任何内容时,我收到错误说明
无法设置未定义的属性'key'
这是我的testRoute文件
module.exports = app => {
app.get("/test",(req, res) => {
// throws error
res.end(req.session.key);
});
};
Ant这就是我让index.js文件知道它的方法。
var app = express();
// Tell Index about my route
require("./routes/authRoutes")(app);
app.set("trust proxy", 1);
app.use(
cookieSession({
name: "session",
secret: "key",
httpOnly: true,
maxAge: 30 * 60 * 1000,
secure: false,
overwrite: false
})
);
我非常擅长表达中间件和路线的概念。
在我的所有路线中访问cookie会话的正确方法是什么。
答案 0 :(得分:0)
我怀疑问题是你在设置会话之前require
路线:
var app = express();
require("./routes/testRoute")(app);
app.set("trust proxy", 1);
//you haven't told your app about the session
require("./routes/testRoute")(app);
///until now....
app.use(
cookieSession({
name: "session",
secret: "key",
httpOnly: true,
maxAge: 30 * 60 * 1000,
secure: false,
overwrite: false
})
);
试试这个
var app = express();
require("./routes/testRoute")(app);
app.set("trust proxy", 1);
app.use(
cookieSession({
name: "session",
secret: "key",
httpOnly: true,
maxAge: 30 * 60 * 1000,
secure: false,
overwrite: false
})
);
//require route after session has been set up
require("./routes/testRoute")(app);
作为一方,Router
可能更适合使用,require
您的路线。
完整详情:https://expressjs.com/en/4x/api.html#router