我试图让 Node.js 中的 session 正常工作,我阅读并尝试了很多有关 Node.js 中 session 的内容,在 PHP 中我可以使用 $_SESSION['key'] = $value;但我可以找到它在 Node.js 中的工作原理。
我正在寻找express-session,它看起来处理cookie相当复杂,并且使用MongoDB或Redis来存储 session 。
所以我会问 somarby 是否可以通过使用 ExpressJS 来简单地分享示例来处理 session ?
因为如果我使用express-session,我需要使用node-uuid来生成我的owen uuid v4 key 。
所以希望我能在这里提供帮助,这是我完成用户登录所需要的。
最佳答案
我使用express-session与 connect-mongo 一起用于将 session 存储在 MongoDB 中。我的代码如下所示:
var express = require('express');
var session = require('express-session');
var mongoStore = require('connect-mongo')({
session: session
});
var cookieExpiration = 30 * (24 * 60 * 60 * 1000); // 1 month
app.use(session({
// When there is nothing on the session, do not save it
saveUninitialized: false,
// Update session if it changes
resave: true,
// Set cookie
cookie: {
// Unsecure
secure: false,
// Http & https
httpOnly: false,
// Domain of the cookie
domain: 'http://localhost:3001',
// Maximum age of the cookie
maxAge: cookieExpiration
},
// Name of your cookie
name: 'testCookie',
// Secret of your cookie
secret: 'someHugeSecret',
// Store the cookie in mongo
store: new mongoStore({
// Store the cookie in mongo
url: 'mongodb://localhost/databaseName',
// Name of the collection
collection: 'sessions'
})
}));
有关快速 session 的所有选项,请参阅文档。
现在您可以将所有 session 数据存储在 req.session
上。您在 session 中放置的所有内容也将保存在 MongoDB 中。还要确保您从前端发送 cookie,否则您的 session 将始终为空。
关于javascript - 在 Node.js 中使用 session 的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724431/