我在我的应用中使用快速会话。我试过的是(POC):.
server.js
app.use(session({
secret: 'pal!lap789',
// create new redis store.
store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 260}),
saveUninitialized: false,
key: 'user_sid',
resave: false,
cookie: { secure: false, httpOnly: false }
}));
app.get('/abcd', sessionChecker, function(req, res){
res.send("hiiiii");
});
app.get('/session', (req, res) => {
req.session.user = "subbuvlb@gmail.com";
res.send("hgdhjdgjds")
});
工作正常,
但是当我尝试与我的项目集成时,它无法正常工作。
app.use(session({
secret: 'pal!lap789',
// create new redis store.
store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 260}),
saveUninitialized: false,
key: 'user_sid',
resave: false,
cookie: { secure: false, httpOnly: false }
}));
var usersRouter = require('./router/users');
app.use('/users', usersRouter);
路由器/ user.js的
const express = require('express'); -------------> New express instantiated.
const router = express.Router();
router.post('/register', (req, res, next) => {
req.session.user = "emailid"
});
我想要实现的是have to check if user session is there for each resquest
,
所以我修改了我的server.js文件,如下所示:
app.use(session({
secret: 'pal!lap789',
// create new redis store.
store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 260}),
saveUninitialized: false,
key: 'user_sid',
resave: false,
cookie: { secure: false, httpOnly: false }
}));
var usersRouter = require('./router/users');
app.use('/users', usersRouter);
var sessionChecker = (req, res, next) => {
console.log(req.session.user) --------------------------->Undefined
if (req.session.user && req.cookies.user_sid) {
next();
} else {
res.redirect('/login');
}
};
var usersRouter = require('./router/users');
app.use('/users',sessionChecker, usersRouter);
为什么req.user.undefined如果我在server.js中指定路由器文件。我想我已经清楚地解释过了,如果需要的话可以提供更多的输入请提供你的想法。提前谢谢。
答案 0 :(得分:0)
在server.js
文件中定义全局变量
global.express = require('express');
global.app = express();
global.session = require('express-session');
app.use(session({
secret: 'pal!lap789',
store: new redisStore({ host: 'localhost', port: 6379, client: client,ttl : 260}),
saveUninitialized: false,
key: 'user_sid',
resave: false,
cookie: { secure: false, httpOnly: false }
}));
var sessionChecker = (req, res, next) => {
if (req.session.user && req.cookies.user_sid) {
next();
} else {
res.redirect('/login');
}
};
var usersRouter = require('./router/users');
app.use('/users',sessionChecker, usersRouter);
在router/user.js
const router = express.Router(); // use global express defined in server.js
router.post('/register', (req, res, next) => {
req.session.user = "emailid"
});
答案 1 :(得分:0)
最后我明白了,
我正在Angular.js
前端进行检查,默认情况下Angular将不包含Cookies
,因此我在Angular前端的每个请求中都设置了{"withCredentials": "true"}
。