node.js express-session 和 cookie-session 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23566555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's difference with express-session and cookie-session?
提问by Tinple
I am new with Express. As Express 4.xhas removed bundled middlewares.
Any middleware I want to use should be required. When I read the README with express-sessionand cookie-sessionon github, I feel it hard to understand the difference.
我是新来的Express。由于Express 4.x已删除捆绑的中间件。我想使用的任何中间件都应该是必需的。当我在github上阅读带有express-session和cookie-session的README时,我觉得很难理解其中的区别。
So I try to write simple code to figure it out. I run twice for each middleware.
所以我尝试编写简单的代码来弄清楚。我为每个中间件运行两次。
var express = require('express')
, cookieParser = require('cookie-parser')
, session = require('cookie-session')
, express_sess = require('express-session')
, app = express();
app.use(cookieParser())
app.use(session({ keys: ['abc'], name: 'user' }));
//app.use(express_sess({ secret: 'abc', key: 'user'}));
app.get('/', function (req, res, next) {
res.end(JSON.stringify(req.cookies));
console.log(req.session)
console.log(req.cookies)
});
app.listen(3000);
For cookie-session, I always get {} in my terminal.
对于cookie-session,我总是在我的终端中获取 {}。
For express-session, I get things like this.
因为express-session,我得到这样的东西。
req.session: { cookie: {
path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true
}
}
req.cookie: {user: 's:aJ97vKA5CCwxqdTj0AV1siRQ.fWusS5+qfCKICtwkfrzcZ/Gq8P0Qdx/kx8mTBhoOhGU'}
It really confuses me. So how to explain the result with the basic use? And what's the difference between them? When should I use them?
这真的让我很困惑。那么如何用基本的用法来解释结果呢?他们之间有什么区别?我应该什么时候使用它们?
回答by bredikhin
Basically, express-sessionis more abstract, it supports different session stores (like files, DB, cache and whatnot).
基本上,express-session更抽象,它支持不同的会话存储(如文件、数据库、缓存等)。
And cookie-sessionis a simple / lightweight cookie-based (cookie is the only storage engine supported: all the session info is stored on the client, in a cookie) session implementation. This kind of sessions is probably most famous for its Rails implementation.
并且cookie-session是一个简单/轻量级的基于 cookie(cookie 是唯一支持的存储引擎:所有会话信息都存储在客户端的 cookie 中)会话实现。这种会话可能以其Rails 实现而闻名。
回答by Doomed93
The basic difference between both these relates to how and where is the session data being stored. Cookie sessionis basically used for lightweight session applications where the session data is stored in a cookie but within the client [browser], whereas, Express Sessionstores just a mere session identifier within a cookie in the client end, whilst storing the session data entirely on the server. Cookie Sessionis helpful in applications where no database is used in the back-end. However, the session data cannot exceed the cookie size. On conditions where a database is used, it acts like a cache to stop frequent database lookups which is expensive.
这两者之间的基本区别与会话数据的存储方式和存储位置有关。 Cookie 会话基本上用于轻量级会话应用程序,其中会话数据存储在 cookie 中但在客户端 [浏览器] 中,而Express Session仅在客户端的 cookie 中存储一个会话标识符,同时完全存储会话数据在服务器上。 Cookie 会话在后端不使用数据库的应用程序中很有用。但是,会话数据不能超过 cookie 大小。在使用数据库的情况下,它就像一个缓存,可以阻止频繁的数据库查找,这是昂贵的。
回答by Abhijeet
express-sessionstores the session identifier in the cookie while the actual session data resides in backend session store like connect-redis, where as cookie-sessionallows you to store the session data in a cookie (client-side).
express-session将会话标识符存储在 cookie 中,而实际会话数据驻留在后端会话存储中,例如connect-redis,其中 ascookie-session允许您将会话数据存储在 cookie(客户端)中。
From the documentation of cookie-session:
从文档cookie-session:
A user session can be stored in two main ways with cookies: on the server or on the client. This module stores the session data on the client within a cookie, while a module like express-session stores only a session identifier on the client within a cookie and stores the session data on the server, typically in a database.
用户会话可以通过 cookie 以两种主要方式存储:在服务器上或在客户端上。该模块将客户端上的会话数据存储在 cookie 中,而像 express-session 这样的模块仅将客户端上的会话标识符存储在 cookie 中,并将会话数据存储在服务器上,通常存储在数据库中。
The main advantage of using cookie-sessionis when you have a clustered node.jsapp, then you don't have to rely on sharing session data between forked processes.
使用的主要优点cookie-session是当您拥有集群node.js应用程序时,您不必依赖于在分叉进程之间共享会话数据。
回答by Gianluca Casati
Let me share an important difference I found: secure cookies.
让我分享我发现的一个重要区别:安全 cookie。
I have a node process behind an nginx proxy which handles SSL.
我在处理 SSL 的 nginx 代理后面有一个节点进程。
I tried with express-session, but I could not enable secure cookies, see issue here.
我尝试使用 express-session,但无法启用安全 cookie,请参阅此处的问题。
Then I tried with almost the same code, but with cookie-sessioninstead, something like
然后我尝试使用几乎相同的代码,但使用cookie-session代替,例如
const expressSession = require('cookie-session')
var expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000); // 7 days
const session = expressSession({
secret: sessionSecret,
resave: false,
saveUninitialized: true,
cookie: {
secureProxy: true,
httpOnly: true,
domain: 'example.com',
expires: expiryDate
}
})
app.use(session)
I just changed require('express-session')to require('cookie-session')and added secureProxy: true,: everything worked out of the box.
我刚换require('express-session')到require('cookie-session')并补充secureProxy: true,:一切工作的开箱即用。
Note also that both packages are maintained by expressjsso probably in my use case I was lucky finding out that cookie-session fits my needs.
另请注意,这两个包均由expressjs维护,因此可能在我的用例中,我很幸运地发现 cookie-session 符合我的需求。
回答by Amjed Omar
The official Express.js documentationrefers to
Express.js 官方文档是指
The main difference between these two modules is how they save cookie session data.
The
express-sessionmiddleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment. In production, you'll need to set up a scalable session-store; see the list of compatible session stores.In contrast,
cookie-sessionmiddleware implements cookie-backed storage: it serializes the entire session to the cookie, rather than just a session key. Only use it when session data is relatively small and easily encoded as primitive values (rather than objects). Although browsers are supposed to support at least 4096 bytes per cookie, to ensure you don't exceed the limit, don't exceed a size of 4093 bytes per domain. Also, be aware that the cookie data will be visible to the client, so if there is any reason to keep it secure or obscure, thenexpress-sessionmay be a better choice.
这两个模块之间的主要区别在于它们如何保存 cookie 会话数据。
该
express-session服务器上的中间件存储会话数据; 它只在 cookie 本身中保存会话 ID,而不是会话数据。默认情况下,它使用内存存储并且不是为生产环境设计的。在生产中,您需要设置一个可扩展的会话存储;查看兼容的会话存储列表。相比之下,
cookie-session中间件实现了 cookie 支持的存储:它将整个会话序列化到 cookie,而不仅仅是一个会话密钥。仅当会话数据相对较小且易于编码为原始值(而不是对象)时才使用它。尽管浏览器应该支持每个 cookie 至少 4096 字节,但为确保不超过限制,每个域的大小不要超过 4093 字节。此外,请注意 cookie 数据将对客户端可见,因此如果有任何理由使其安全或隐蔽,那么express-session可能是更好的选择。
回答by LeoGonzalez
The get a non-empty console.log(req.session) you need to set session values before logging.
获取非空的 console.log(req.session) 您需要在登录之前设置会话值。
From the cookie-session repo (https://github.com/expressjs/cookie-session):
来自 cookie-session 存储库(https://github.com/expressjs/cookie-session):
app.get('/', function (req, res, next) {
req.session.views = (req.session.views || 0) + 1
console.log(req.session)
res.end(req.session.views + ' views')
})
If you never set any info on the req.session object, it will return empty.
如果您从未在 req.session 对象上设置任何信息,它将返回空。
回答by u11056376
v4-> cookie-session is (Establish cookie-based sessions.) equals in ->v3 express.cookieSession
v4-> cookie-session 是(建立基于 cookie 的会话。)等于 ->v3 express.cookieSession
v4-> express-session is (Establish server-based sessions (development only)). equals in ->v3 express.session
v4-> express-session 是(建立基于服务器的会话(仅限开发))。等于 ->v3 express.session

