从另一个端点检索时,使用 express-session 保存到 req.session 的数据为空
Posted
技术标签:
【中文标题】从另一个端点检索时,使用 express-session 保存到 req.session 的数据为空【英文标题】:Data saved to req.session using express-session is empty when retrieved from another endpoint 【发布时间】:2021-09-06 09:55:28 【问题描述】:我正在实现快速会话的简单使用,并将当前登录的用户保存到会话中。当我在get
路由上将其记录到控制台时,会话具有currentUser
键,但该值只是一个空对象,如果我在保存req.session
会话的中间件上记录currentUser
有正确的数据。看起来数据没有持久化,但我觉得奇怪的是它有键,但没有值。
我省略了与问题无关的部分代码。
// saveLoggedInUser middleware
const saveLoggedInUser = async (req, res, next) =>
const User = await req.body;
req.session.currentUser = User;
req.session.save();
console.log(req.session.currentUser); // Logs correct data
//const usersFromDB = await fetchUsersFromDB().catch((e) => console.log(e));
//findCommonUser(usersFromDB,User);
//app.set('Users', User);
next();
;
// GetUserInvoices
userInvoices.get('/fetchUserInvoices', async (req,res) =>
try
const invoices = await InvoiceModel.find().catch((e) => console.log(e));
const user = req.session.currentUser;
console.log(user); // logs the empty object value.
catch (error)
console.log(error)
// server.js
app.use(express.json());
app.use(cors());
app.use(express.static(path.join(__dirname, 'build')));
app.use('/', cookieValidationMiddleware, StoreInvoiceRouter);
app.use(expressSession(
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: secure: false
));
app.use('/', saveLoggedInUserMiddleware, UserInvoicesRouter);
app.use('/', UpdateUserProfileRouter);
app.get('*', async (req,res) =>
res.sendFile(path.join(__dirname, 'build', 'index.html'));
);
【问题讨论】:
【参考方案1】:问题在于saveLoggedInUser
没有附加方法。下面是我使用的最终代码。
// server.js
app.use(
expressSession(
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
)
);
app.use(express.json());
app.use(cors());
app.use(express.static(path.join(__dirname, 'build')));
app.use('/', cookieValidationMiddleware, StoreInvoiceRouter);
app.use('/', saveLoggedInUserMiddleware, UserInvoicesRouter);
app.use('/', UpdateUserProfileRouter);
app.get('*', async (req,res) =>
res.sendFile(path.join(__dirname, 'build', 'index.html'));
);
//saveLoggedInUser Middleware
saveLoggedInUser.post('/saveUser', async (req,res,next) =>
const User = await req.body;
req.session.currentUser = User;
const usersFromDB = await fetchUsersFromDB().catch((e) => console.log(e));
findCommonUser(usersFromDB,User);
next();
)
// getUserInvoices
userInvoices.get('/fetchUserInvoices', async (req,res) =>
try
const invoices = await InvoiceModel.find().catch((e) => console.log(e));
const user = req.session.currentUser;
console.log('USER',user);
const userInvoices = await app.get('userInvoices')
req.session.invoices = userInvoices
var currentInvoices = req.session.invoices;
res.json(currentInvoices);
catch (error)
console.log(error)
);
【讨论】:
以上是关于从另一个端点检索时,使用 express-session 保存到 req.session 的数据为空的主要内容,如果未能解决你的问题,请参考以下文章