This is a Node.js module available through the npm registry. 这是一个Node.js模块,可通过npm注册表获得。Installation is done using the 使用npm install
command:npm install
命令完成安装:
$ npm install express-session
var session = require('express-session')
Create a session middleware with the given 使用给定的options
.options
创建会话中间件。
Note Session data is not saved in the cookie itself, just the session ID. 注意:会话数据不保存在cookie本身中,只保存会话ID。Session data is stored server-side.会话数据存储在服务器端。
Note Since version 1.5.0, the 自版本1.5.0以来,该模块不再需要使用cookie-parser
middleware no longer needs to be used for this module to work. cookie-parser
中间件来工作。This module now directly reads and writes cookies on 该模块现在直接读取和写入req
/res
. req
/res
上的cookie。Using 如果此模块与cookie-parser
may result in issues if the secret
is not the same between this module and cookie-parser
.cookie-parser
之间的secret
不同,则使用cookie-parser
可能会导致问题。
Warning The default server-side session storage, 默认的服务器端会话存储MemoryStore
, is purposely not designed for a production environment. MemoryStore
不是专门为生产环境设计的。It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.它在大多数情况下都会泄漏内存,不会扩展到单个进程,并且用于调试和开发。
For a list of stores, see compatible session stores.有关存储列表,请参阅兼容会话存储。
express-session
accepts these properties in the options object.在选项对象中接受这些属性。
Settings object for the session ID cookie. 会话ID cookie的设置对象。The default value is 默认值为{ path: '/', httpOnly: true, secure: false, maxAge: null }
.{ path: '/', httpOnly: true, secure: false, maxAge: null }
。
The following are options that can be set in this object.以下是可以在此对象中设置的选项。
Specifies the value for the 指定Domain
Set-Cookie
attribute. Domain
Set-Cookie
属性的值。By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.默认情况下,没有设置域,并且大多数客户端将考虑Cookie仅适用于当前域。
Specifies the 指定Date
object to be the value for the Expires
Set-Cookie
attribute. Date
对象作为Expires
Set-Cookie
属性的值。By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application.默认情况下,没有设置过期,大多数客户会认为这是“非持久性Cookie”,并会在退出Web浏览器应用程序的条件下删除它。
Note If both 如果在选项中同时设置了expires
and maxAge
are set in the options, then the last one defined in the object is what is used.expires
和maxAge
,则使用对象中定义的最后一个。
Note The expires
option should not be set directly; instead only use the maxAge
option.expires
选项不应直接设置;相反,应只使用maxAge
选项。
Specifies the 指定boolean
value for the HttpOnly
Set-Cookie
attribute. HttpOnly
Set-Cookie
属性的布尔值。When truthy, the 当truthy时,设置HttpOnly
attribute is set, otherwise it is not. HttpOnly
属性,否则不设置。By default, the 默认情况下,设置了HttpOnly
attribute is set.HttpOnly
属性。
Note be careful when setting this to 将其设置为true
, as compliant clients will not allow client-side JavaScript to see the cookie in document.cookie
.true
时要小心,因为兼容客户端将不允许客户端JavaScript在document.cookie
中看到cookie。
Specifies the 指定计算number
(in milliseconds) to use when calculating the Expires
Set-Cookie
attribute. Expires
Set-Cookie
属性时使用的数字(以毫秒为单位)。This is done by taking the current server time and adding 这是通过获取当前服务器时间并将maxAge
milliseconds to the value to calculate an Expires
datetime. maxAge
毫秒添加到值以计算Expires
datetime来完成的。By default, no maximum age is set.默认情况下,未设置最大年龄。
Note If both 如果在选项中同时设置了expires
and maxAge
are set in the options, then the last one defined in the object is what is used.expires
和maxAge
,则使用对象中定义的最后一个。
Specifies the value for the 指定Path
Set-Cookie
. Path
Set-Cookie
的值。By default, this is set to 默认情况下,该值设置为“/”,这是域的根路径。'/'
, which is the root path of the domain.
Specifies the 指定boolean
or string
to be the value for the SameSite
Set-Cookie
attribute.boolean
或string
作为SameSite
Set-Cookie
属性的值。
true
will set the SameSite
attribute to Strict
for strict same site enforcement.true
,则会将SameSite
属性设置为Strict
,以严格执行同一站点。false
will not set the SameSite
attribute.false
不会设置SameSite
属性。'lax'
SameSite
attribute to Lax
for lax same site enforcement.SameSite
属性设置为Lax
,用于松散同一站点强制。'none'
SameSite
attribute to None
for an explicit cross-site cookie.SameSite
属性设置为None
。'strict'
SameSite
attribute to Strict
for strict same site enforcement.SameSite
属性设置为Strict
,以严格执行同一站点。More information about the different enforcement levels can be found in the specification.有关不同实施级别的更多信息,请参阅规范文档。
Note This is an attribute that has not yet been fully standardized, and may change in the future. 注意:这是一个尚未完全标准化的属性,将来可能会更改。This also means many clients may ignore this attribute until they understand it.这也意味着许多客户端可能会忽略此属性,直到他们理解它为止。
Note There is a draft spec that requires that the 有一个草案规范,要求在Secure
attribute be set to true
when the SameSite
attribute has been set to 'none'
. SameSite
属性设置为'none'
时将Secure
属性设置为true
。Some web browsers or other clients may be adopting this specification.某些web浏览器或其他客户端可能正在采用此规范。
Specifies the 指定 boolean
value for the Secure
Set-Cookie
attribute. Secure
Set-Cookie
属性的布尔值。When truthy, the 当truthy时,设置Secure
attribute is set, otherwise it is not. Secure
属性,否则不设置。By default, the 默认情况下,未设置Secure
attribute is not set.Secure
属性。
Note be careful when setting this to 注意:将此设置为true
, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection.true
时要小心,因为如果浏览器没有HTTPS连接,兼容的客户端将来不会将cookie发送回服务器。
Please note that 请注意,建议使用secure: true
is a recommended option. secure:true
。However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. 但是,它需要一个支持https的网站,即https是安全cookie所必需的。If 如果设置了secure
is set, and you access your site over HTTP, the cookie will not be set. secure
,并且您通过HTTP访问站点,则不会设置cookie。If you have your node.js behind a proxy and are using 如果您的node.js位于代理之后,并且使用secure: true
, you need to set "trust proxy" in express:secure:true
,则需要在express中设置“trust proxy”:
var app = express()
app.set('trust proxy', 1) // trust first proxy
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}))
For using secure cookies in production, but allowing for testing in development, the following is an example of enabling this setup based on 对于在生产中使用安全cookie,但允许在开发中进行测试,以下是基于express中的NODE_ENV
in express:NODE_ENV
启用此设置的示例:
var app = express()
var sess = {
secret: 'keyboard cat',
cookie: {}
}
if (app.get('env') === 'production') {
app.set('trust proxy', 1) // trust first proxy
sess.cookie.secure = true // serve secure cookies
}
app.use(session(sess))
The 还可以将cookie.secure
option can also be set to the special value 'auto'
to have this setting automatically match the determined security of the connection. cookie.secure
选项设置为特殊值'auto'
,使此设置自动与确定的连接安全性匹配。Be careful when using this setting if the site is available both as HTTP and HTTPS, as once the cookie is set on HTTPS, it will no longer be visible over HTTP. 如果站点同时以HTTP和HTTPS的形式可用,则在使用此设置时要小心,因为一旦在HTTPS上设置cookie,它将不再通过HTTP可见。This is useful when the Express 当正确设置"trust proxy"
setting is properly setup to simplify development vs production configuration."trust proxy"
设置以简化开发与生产配置时,这非常有用。
Function to call to generate a new session ID. Provide a function that returns a string that will be used as a session ID. 要调用以生成新会话ID的函数。提供一个返回将用作会话ID的字符串的函数。The function is given 如果要在生成ID时使用附加到req
as the first argument if you want to use some value attached to req
when generating the ID.req
的某个值,则函数将req
作为第一个参数。
The default value is a function which uses the 默认值是使用uid-safe
library to generate IDs.uid-safe
生成ID的函数。
NOTE be careful to generate unique IDs so your sessions do not conflict.小心生成唯一的ID,这样会话就不会冲突。
app.use(session({
genid: function(req) {
return genuuid() // use UUIDs for session IDs
},
secret: 'keyboard cat'
}))
The name of the session ID cookie to set in the response (and read from in the request).要在响应中设置(并从请求中读取)的会话ID cookie的名称。
The default value is 默认值为'connect.sid'
.'connect.sid'
。
Note if you have multiple apps running on the same hostname (this is just the name, i.e. 注意:如果在同一主机名上运行多个应用程序(这只是名称,即localhost
or 127.0.0.1
; different schemes and ports do not name a different hostname), then you need to separate the session cookies from each other. localhost
或127.0.0.1
;不同的方案和端口不会命名不同的主机名),则需要将会话cookie彼此分离。The simplest method is to simply set different 最简单的方法是简单地为每个应用程序设置不同的name
s per app.name
。
Trust the reverse proxy when setting secure cookies (via the "X-Forwarded-Proto" header).设置安全cookie时信任反向代理(通过“X-Forwarded-Proto”标头)。
The default value is 默认值undefined
.undefined
。
true
false
undefined
Forces the session to be saved back to the session store, even if the session was never modified during the request. 强制将会话保存回会话存储,即使在请求期间从未修改过会话。Depending on your store this may be necessary, but it can also create race conditions where a client makes two parallel requests to your server and changes made to the session in one request may get overwritten when the other request ends, even if it made no changes (this behavior also depends on what store you're using).根据您的存储,这可能是必要的,但它也会创建竞争条件,即客户端向您的服务器发出两个并行请求,并且在一个请求中对会话所做的更改可能会在另一个请求结束时被覆盖,即使它没有做出任何更改(此行为还取决于您使用的存储)。
The default value is 默认值为true
, but using the default has been deprecated, as the default will change in the future. true
,但不推荐使用默认值,因为默认值将在将来更改。Please research into this setting and choose what is appropriate to your use-case. 请研究此设置并选择适合您的用例的设置。Typically, you'll want 通常,您需要false
.false
。
How do I know if this is necessary for my store? 我如何知道这对我的店铺是否有必要?The best way to know is to check with your store if it implements the 最好的了解方法是与您的商店核实是否实施了touch
method. touch
方法。If it does, then you can safely set 如果是,则可以安全地设置resave: false
. resave: false
。If it does not implement the 如果它没有实现touch方法,并且您的存储设置了存储会话的过期日期,那么您可能需要touch
method and your store sets an expiration date on stored sessions, then you likely need resave: true
.resave: true
。
Force the session identifier cookie to be set on every response. 强制在每个响应上设置会话标识符cookie。The expiration is reset to the original maxAge, resetting the expiration countdown.过期时间重置为原始maxAge,重置过期倒计时。
The default value is 默认值为false
.false
。
With this enabled, the session identifier cookie will expire in maxAge since the last response was sent instead of in maxAge since the session was last modified by the server.启用此选项后,会话标识符cookie将在上次发送响应后的maxAge中过期,而不是在服务器上次修改会话后的maxAge中过期。
This is typically used in conjuction with short, non-session-length maxAge values to provide a quick timeout of the session data with reduced potential of it occurring during on going server interactions.这通常与短的、非会话长度的maxAge结合使用,以提供会话数据的快速超时,同时减少在进行中的服务器交互期间发生会话数据的可能性。
Note When this option is set to 如果此选项设置为true
but the saveUninitialized
option is set to false
, the cookie will not be set on a response with an uninitialized session. true
,但saveUninitialized
选项设置为false
,则不会在具有未初始化会话的响应上设置cookie。This option only modifies the behavior when an existing session was loaded for the request.此选项仅在为请求加载现有会话时修改行为。
Forces a session that is "uninitialized" to be saved to the store. 强制将“未初始化”的会话保存到存储中。A session is uninitialized when it is new but not modified. 当会话是新的但未被修改时,它将被取消初始化。Choosing 选择false
is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie. false
对于实现登录会话、减少服务器存储使用或遵守在设置cookie之前需要权限的法律非常有用。Choosing 选择false
will also help with race conditions where a client makes multiple parallel requests without a session.false
也将有助于解决客户机在没有会话的情况下发出多个并行请求的竞争条件。
The default value is 默认值为true
, but using the default has been deprecated, as the default will change in the future. true
,但不推荐使用默认值,因为默认值将在将来更改。Please research into this setting and choose what is appropriate to your use-case.请研究此设置并选择适合您的用例的设置。
Note if you are using Session in conjunction with PassportJS, Passport will add an empty Passport object to the session for use after a user is authenticated, which will be treated as a modification to the session, causing it to be saved. 如果您将会话与PassportJS结合使用,Passport将向会话中添加一个空Passport对象,以便在对用户进行身份验证后使用,这将被视为对会话的修改,从而保存该会话。This has been fixed in PassportJS 0.3.0这已在PassportJS 0.3.0中修复
Required option
This is the secret used to sign the session ID cookie. 这是用于对会话ID cookie进行签名的秘密。This can be either a string for a single secret, or an array of multiple secrets. 这可以是单个机密的字符串,也可以是多个机密的数组。If an array of secrets is provided, only the first element will be used to sign the session ID cookie, while all the elements will be considered when verifying the signature in requests. 如果提供了一个秘密数组,则只有第一个元素将用于对会话ID cookie进行签名,而在验证请求中的签名时将考虑所有元素。The secret itself should be not easily parsed by a human and would best be a random set of characters. A best practice may include:秘密本身不应该很容易被人解析,最好是一组随机字符。最佳做法可包括:
Using a secret that cannot be guessed will reduce the ability to hijack a session to only guessing the session ID (as determined by the 使用无法猜测的秘密将使劫持会话的能力降低到只能猜测会话ID(由genid
option).genid
选项确定)。
Changing the secret value will invalidate all existing sessions. 更改机密值将使所有现有会话无效。In order to rotate the secret without invalidating sessions, provide an array of secrets, with the new secret as first element of the array, and including previous secrets as the later elements.为了在不使会话无效的情况下旋转机密,请提供一个机密数组,其中新机密作为数组的第一个元素,并包括以前的机密作为后面的元素。
The session store instance, defaults to a new 会话存储实例默认为新的MemoryStore
instance.MemoryStore
实例。
Control the result of unsetting 控制取消设置req.session
(through delete
, setting to null
, etc.).req.session
的结果(通过delete
、设置为null
等)。
The default value is 默认值为'keep'
.'keep'
。
'destroy'
'keep'
To store or access session data, simply use the request property 要存储或访问会话数据,只需使用请求属性req.session
, which is (generally) serialized as JSON by the store, so nested objects are typically fine. req.session
,该属性(通常)由存储序列化为JSON,因此嵌套对象通常很好。For example below is a user-specific view counter:例如,下面是一个特定于用户的视图计数器:
// Use the session middleware使用会话中间件
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))
// Access the session as req.session以req.session的形式访问会话
app.get('/', function(req, res, next) {
if (req.session.views) {
req.session.views++
res.setHeader('Content-Type', 'text/html')
res.write('<p>views: ' + req.session.views + '</p>')
res.write('<p>expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>')
res.end()
} else {
req.session.views = 1
res.end('welcome to the session demo. refresh!')
}
})
To regenerate the session simply invoke the method. 要重新生成会话,只需调用该方法。Once complete, a new SID and 完成后,新的SID和Session
instance will be initialized at req.session
and the callback
will be invoked.Session
实例将在req.Session
处初始化,并调用callback
。
req.session.regenerate(function(err) {
// will have a new session here
})
Destroys the session and will unset the 销毁会话并将取消设置req.session
property. req.session
属性。Once complete, the 完成后,将调用callback
will be invoked.callback
。
req.session.destroy(function(err) {
// cannot access session here无法在此访问会话
})
Reloads the session data from the store and re-populates the 从存储区重新加载会话数据并重新填充req.session
object. req.session
对象。Once complete, the 完成后,将调用callback
will be invoked.callback
。
req.session.reload(function(err) {
// session updated
})
Save the session back to the store, replacing the contents on the store with the contents in memory (though a store may do something else--consult the store's documentation for exact behavior).将会话保存回存储区,用内存中的内容替换存储区中的内容(尽管存储区可能会执行其他操作——请参阅存储区的文档了解确切行为)。
This method is automatically called at the end of the HTTP response if the session data has been altered (though this behavior can be altered with various options in the middleware constructor). 如果会话数据已更改,则在HTTP响应结束时自动调用此方法(尽管此行为可以通过中间件构造函数中的各种选项进行更改)。Because of this, typically this method does not need to be called.因此,通常不需要调用此方法。
There are some cases where it is useful to call this method, for example, redirects, long-lived requests or in WebSockets.在某些情况下,调用此方法很有用,例如重定向、长期请求或在WebSocket中。
req.session.save(function(err) {
// session saved
})
Updates the 更新.maxAge
property. .maxAge
属性。Typically this is not necessary to call, as the session middleware does this for you.通常,这不需要调用,因为会话中间件会为您执行此操作。
Each session has a unique ID associated with it. 每个会话都有一个与之关联的唯一ID。This property is an alias of req.sessionID and cannot be modified. 此属性是req.sessionID
的别名,无法修改。It has been added to make the session ID accessible from the 添加它是为了使会话ID可以从session
object.session
对象访问。
Each session has a unique cookie object accompany it. 每个会话都有一个唯一的cookie对象。This allows you to alter the session cookie per visitor. 这允许您更改每个访问者的会话cookie。For example we can set 例如,我们可以将req.session.cookie.expires
to false
to enable the cookie to remain for only the duration of the user-agent.req.session.cookie.expires
设置为false
,以使cookie仅在用户代理期间保持。
Alternatively 或者req.session.cookie.maxAge
will return the time remaining in milliseconds, which we may also re-assign a new value to adjust the .expires
property appropriately. req.session.cookie.maxAge
将返回以毫秒为单位的剩余时间,我们还可以重新分配一个新值以适当调整.expires
属性。The following are essentially equivalent以下内容本质上是等效的
var hour = 3600000
req.session.cookie.expires = new Date(Date.now() + hour)
req.session.cookie.maxAge = hour
For example when maxAge
is set to 60000
(one minute), and 30 seconds has elapsed it will return 30000
until the current request has completed, at which time req.session.touch()
is called to reset req.session.cookie.maxAge
to its original value.
req.session.cookie.maxAge // => 30000
The req.session.cookie.originalMaxAge
property returns the original maxAge
(time-to-live), in milliseconds, of the session cookie.
To get the ID of the loaded session, access the request property 要获取加载会话的ID,请访问请求属性req.sessionID
. req.sessionID
。This is simply a read-only value set when a session is loaded/created.这只是在加载/创建会话时设置的只读值。
Every session store must be an 每个会话存储都必须是EventEmitter
and implement specific methods. EventEmitter
并实现特定的方法。The following methods are the list of required, recommended, and optional.以下方法是必需、推荐和可选的方法列表。
For an example implementation view the connect-redis repo.有关示例实现视图,请参阅connect-redis repo。
Optional可选
This optional method is used to get all sessions in the store as an array. 此可选方法用于将存储中的所有会话作为数组获取。The callback
should be called as callback(error, sessions)
.callback
应以callback(error, sessions)
的形式调用。
Required必需
This required method is used to destroy/delete a session from the store given a session ID (此必需方法用于在给定会话ID(sid
). sid
)的情况下从存储中销毁/删除会话。The 一旦会话被破坏,callback
should be called as callback(error)
once the session is destroyed.callback
应该以callback(error)
的形式调用。
Optional可选
This optional method is used to delete all sessions from the store. 此可选方法用于从存储中删除所有会话。The 一旦存储区被清除,callback
should be called as callback(error)
once the store is cleared.callback
应被以callback(error)
的形式调用。
Optional可选
This optional method is used to get the count of all sessions in the store. 此可选方法用于获取存储中所有会话的计数。The callback
should be called as callback(error, len)
.callback
应该以callback(error, session)
的形式调用。
Required必需
This required method is used to get a session from the store given a session ID (此必需方法用于从给定会话ID(sid
). sid
)的存储中获取会话。The callback
should be called as callback(error, session)
.callback
应该以callback(error, session)
的形式调用。
The 如果找到会话,则session
argument should be a session if found, otherwise null
or undefined
if the session was not found (and there was no error). session
参数应为会话;否则,如果未找到会话(并且没有错误),则为null
或未定义。A special case is made when 当error.code === 'ENOENT'
to act like callback(null, null)
.error.code === 'ENOENT'
起到callback(null, null)
的作用时,会出现一种特殊情况。
Required必需
This required method is used to upsert a session into the store given a session ID (此必需的方法用于在给定会话ID(sid
) and session (session
) object. sid
)和会话(session
)对象的情况下将会话向存储中插入。The callback should be called as 在存储区中设置会话后,callback(error)
once the session has been set in the store.callback
应该以callback(error)
的形式调用。
Recommended推荐
This recommended method is used to "touch" a given session given a session ID (建议使用此方法“触摸”给定会话ID(sid
) and session (session
) object. sid
)和会话(session
)对象的给定会话。The 一旦接触到会话,callback
should be called as callback(error)
once the session has been touched.callback
应该以callback(error)
的形式调用。
This is primarily used when the store will automatically delete idle sessions and this method is used to signal to the store the given session is active, potentially resetting the idle timer.这主要用于存储将自动删除空闲会话时,此方法用于向存储发出给定会话处于活动状态的信号,可能会重置空闲计时器。
The following modules implement a session store that is compatible with this module. 以下模块实现了与此模块兼容的会话存储。Please make a PR to add additional modules :)请制作PR以添加其他模块:)
aerospike-session-store A session store using Aerospike.
better-sqlite3-session-store A session store based on better-sqlite3.
cassandra-store An Apache Cassandra-based session store.
cluster-store A wrapper for using in-process / embedded stores - such as SQLite (via knex), leveldb, files, or memory - with node cluster (desirable for Raspberry Pi 2 and other multi-core embedded devices).
connect-arango An ArangoDB-based session store.
connect-azuretables An Azure Table Storage-based session store.
connect-cloudant-store An IBM Cloudant-based session store.
connect-couchbase A couchbase-based session store.
connect-datacache An IBM Bluemix Data Cache-based session store.
@google-cloud/connect-datastore A Google Cloud Datastore-based session store.
connect-db2 An IBM DB2-based session store built using ibm_db module.
connect-dynamodb A DynamoDB-based session store.
@google-cloud/connect-firestore A Google Cloud Firestore-based session store.
connect-hazelcast Hazelcast session store for Connect and Express.
connect-loki A Loki.js-based session store.
connect-memcached A memcached-based session store.
connect-memjs A memcached-based session store using memjs as the memcached client.
connect-ml A MarkLogic Server-based session store.
connect-monetdb A MonetDB-based session store.
connect-mongo A MongoDB-based session store.
connect-mongodb-session Lightweight MongoDB-based session store built and maintained by MongoDB.
connect-mssql-v2 A Microsoft SQL Server-based session store based on connect-mssql.
connect-pg-simple A PostgreSQL-based session store.
connect-redis A Redis-based session store.
connect-session-firebase A session store based on the Firebase Realtime Database
connect-session-knex A session store using Knex.js, which is a SQL query builder for PostgreSQL, MySQL, MariaDB, SQLite3, and Oracle.
connect-session-sequelize A session store using Sequelize.js, which is a Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL.
connect-sqlite3 A SQLite3 session store modeled after the TJ's
connect-redis
store.
connect-typeorm A TypeORM-based session store.
couchdb-expression A CouchDB-based session store.
dynamodb-store A DynamoDB-based session store.
express-etcd An etcd based session store.
express-mysql-session A session store using native MySQL via the node-mysql module.
express-nedb-session A NeDB-based session store.
express-oracle-session A session store using native oracle via the node-oracledb module.
express-session-cache-manager A store that implements cache-manager, which supports a variety of storage types.
express-session-etcd3 An etcd3 based session store.
express-session-level A LevelDB based session store.
express-session-rsdb Session store based on Rocket-Store: A very simple, super fast and yet powerfull, flat file database.
express-sessions A session store supporting both MongoDB and Redis.
firestore-store A Firestore-based session store.
fortune-session A Fortune.js based session store. Supports all backends supported by Fortune (MongoDB, Redis, Postgres, NeDB).
hazelcast-store A Hazelcast-based session store built on the Hazelcast Node Client.
level-session-store A LevelDB-based session store.
lowdb-session-store A lowdb-based session store.
medea-session-store A Medea-based session store.
memorystore A memory session store made for production.
mssql-session-store A SQL Server-based session store.
nedb-session-store An alternate NeDB-based (either in-memory or file-persisted) session store.
@quixo3/prisma-session-store A session store for the Prisma Framework.
restsession Store sessions utilizing a RESTful API
sequelstore-connect A session store using Sequelize.js.
session-file-store A file system-based session store.
session-pouchdb-store Session store for PouchDB / CouchDB. Accepts embedded, custom, or remote PouchDB instance and realtime synchronization.
session-rethinkdb A RethinkDB-based session store.
@databunker/session-store A Databunker-based encrypted session store.
sessionstore A session store that works with various databases.
tch-nedb-session A file system session store based on NeDB.
A simple example using 使用express-session
to store page views for a user.express-session
为用户存储页面视图的简单示例。
var express = require('express')
var parseurl = require('parseurl')
var session = require('express-session')
var app = express()
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
app.use(function (req, res, next) {
if (!req.session.views) {
req.session.views = {}
}
// get the url pathname
var pathname = parseurl(req).pathname
// count the views
req.session.views[pathname] = (req.session.views[pathname] || 0) + 1
next()
})
app.get('/foo', function (req, res, next) {
res.send('you viewed this page ' + req.session.views['/foo'] + ' times')
})
app.get('/bar', function (req, res, next) {
res.send('you viewed this page ' + req.session.views['/bar'] + ' times')
})
This module uses the debug module internally to log information about session operations.此模块在内部使用debug模块记录有关会话操作的信息。
To see all the internal logs, set the 要查看所有内部日志,请在启动应用程序时将DEBUG
environment variable to express-session
when launching your app (npm start
, in this example):DEBUG
环境变量设置为express-session
(本例中为npm start
):
$ DEBUG=express-session npm start
On Windows, use the corresponding command;在Windows上,使用相应的命令;
> set DEBUG=express-session & npm start