gpt4 book ai didi

javascript - session 不工作 + 快速

转载 作者:行者123 更新时间:2023-11-30 06:25:18 26 4
gpt4 key购买 nike

我在我的应用程序中使用快速 session 。我尝试过的是 (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);

router/user.js

const express = require('express');  -------------> New express instantiated.
const router = express.Router();
router.post('/register', (req, res, next) => {
req.session.user = "emailid"
});

我想要实现的是必须检查每个请求是否存在用户 session

所以我修改了我的 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);

如果我在 server.js 中指定路由器文件,为什么会出现 req.user.undefined。我想我解释清楚了,准备好在需要时提供更多意见。请提供你的想法。提前致谢。

最佳答案

在你的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"
});

关于javascript - session 不工作 + 快速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50836586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com