我在节点js和express 4中遇到了快速会话的问题。我在routes / index.js中设置了一个会话变量,并且在另一个路由文件users.js上的app.js.But中不可用。
var sess;
router.get('/setsession',function(req,res){
sess=req.session;
sess.username="safeer";
res.send("hi "+sess.username);
});
router.get('/getsession',function(req,res){
sess=req.session;
res.send("hi "+sess.username); //here session value available
});
var sess;
router.get('/session3',function(req,res){
sess=req.session;
res.send("hi "+sess.username); // here also session is available
});
var session = require('express-session');
app.use(session({secret: 'secret',saveUninitialized: true,resave: true}));
var sess;
app.get('/session1',function(req,res){
sess=req.session;
res.send("hi "+sess.username); //here session is undefined
});
app.use('/', routes);
app.use('/users', users);
请有人给我一个解决方案吗。 ?
答案 0 :(得分:2)
我建议您在会话中设置用户名:
在routes / index.js
中router.get('/setsession',function(req,res){
req.session.username="safeer";
res.send("hi "+ req.session.username);
});
在app.js
app.get('/session1',function(req,res){
res.send("hi "+ req.session.username); //get from session. Can be set in variable too
});