Installation
This is a Node.js module available through the npm registry. Installation is done using the npm install command:
$ npm install express-session
API var session = require('express-session')
session(options)
Create a session middleware with the given options.
使用给定的选项创建会话中间件。
Note Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side.
注意:会话数据不保存在cookie本身中,只保存会话ID。会话数据存储在服务器端。
Note Since version 1.5.0, the cookie-parser middleware no longer needs to be used for this module to work. This module now directly reads and writes cookies on req/res. Using cookie-parser may result in issues if the secret is not the same between this module and cookie-parser.
注意:自1.5.0版以来,该模块不再需要使用cookie解析器中间件来工作。此模块现在直接在req/res上读取和写入cookie。如果此模块和cookie解析器之间的秘密不同,则使用cookie解析器可能会导致问题。
Warning The default server-side session storage, MemoryStore, is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing.
警告:默认的服务器端会话存储MemoryStore不是专门为生产环境设计的。它在大多数情况下都会泄漏内存,不能扩展到单个进程,用于调试和开发。
For a list of stores, see compatible session stores.
有关存储列表,请参阅兼容会话存储。
Options
express-session accepts these properties in the options object.
express session在options对象中接受这些属性。
cookie
Settings object for the session 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.
以下是可以在此对象中设置的选项:
cookie.domain
Specifies the value for the Domain Set-Cookie attribute. By default, no domain is set, and most clients will consider the cookie to apply to only the current domain.
cookie.expires
Specifies the Date object to be the value for the Expires Set-Cookie attribute. 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属性的值。默认情况下,没有设置域,并且大多数客户端将考虑Cookie仅适用于当前域。
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选项。
cookie.httpOnly
Specifies the boolean value for the HttpOnly Set-Cookie attribute. When truthy, the HttpOnly attribute is set, otherwise it is not. By default, the HttpOnly attribute is set.
指定HttpOnly Set Cookie属性的布尔值。当truthy时,设置HttpOnly属性,否则不设置。默认情况下,设置了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时要小心,因为兼容的客户端不允许
cookie.maxAge
Specifies the number (in milliseconds) to use when calculating the Expires Set-Cookie attribute. This is done by taking the current server time and adding maxAge milliseconds to the value to calculate an Expires datetime. By default, no maximum age is set.
指定计算Expires Set Cookie属性时使用的数字(以毫秒为单位)。这是通过获取当前服务器时间并将maxAge毫秒添加到该值来计算Expires datetime来完成的。默认情况下,没有设置最大年龄。
Note If both expires and maxAge are set in the options, then the last one defined in the object is what is used.
cookie.path
Specifies the value for the Path Set-Cookie. By default, this is set to '/', which is the root path of the domain.
指定路径集Cookie的值。默认情况下,它被设置为“/”,这是域的根路径。
cookie.sameSite
Specifies the boolean or string to be the value for the SameSite Set-Cookie attribute.
指定布尔值或字符串作为SameSite Set Cookie属性的值。
true will set the SameSite attribute to Strict for strict same site enforcement.
false will not set the SameSite attribute.
true会将SameSite属性设置为Strict,以严格执行同一站点。
false不会设置SameSite属性。
'lax' will set the SameSite attribute to Lax for lax same site enforcement.
'none' will set the SameSite attribute to None for an explicit cross-site cookie.
'strict' will set the SameSite attribute to Strict for strict same site enforcement.
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'. Some web browsers or other clients may be adopting this specification.
注意,有一个草案规范要求当SameSite属性被设置为“无”时,安全属性被设置为true。某些web浏览器或其他客户端可能正在采用此规范。
cookie.secure
Specifies the boolean value for the Secure Set-Cookie attribute. When truthy, the Secure attribute is set, otherwise it is not. By default, the Secure attribute is not set.
指定安全集Cookie属性的布尔值。当truthy时,设置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. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set. If you have your node.js behind a proxy and are using secure: true, you need to set "trust proxy" in express:
请注意,建议使用secure:true。然而,它需要一个支持https的网站,也就是说,https是安全cookie所必需的。如果设置了安全,并且您通过HTTP访问站点,则不会设置cookie。如果你有你的节点。js在一个代理后面,并且正在使用secure:true,您需要在express中设置“信任代理”:
案例:
var app = express()app.set('trust proxy', 1) // trust first proxyapp.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 NODE_ENV in express:
为了在生产中使用安全cookie,但允许在开发中进行测试,以下是基于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. 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. This is useful when the Express "trust proxy" setting is properly setup to simplify development vs production configuration.
也可以设置为特殊值“auto”,使此设置自动匹配已确定的连接安全性。如果站点既可以作为HTTP也可以作为HTTPS使用,那么在使用此设置时要小心,因为一旦cookie设置为HTTPS,它将不再通过HTTP可见。当正确设置Express“trust proxy”设置以简化开发与生产配置时,这非常有用。
genid
Function to call to generate a new session ID. Provide a function that returns a string that will be used as a session ID. The function is given req as the first argument if you want to use some value attached to req when generating the ID.
The default value is a function which uses the uid-safe library to generate IDs.
NOTE be careful to generate unique IDs so your sessions do not conflict.
函数调用以生成新的会话ID。提供一个函数,该函数返回一个字符串,该字符串将用作会话ID。如果您想在生成ID时使用附加到req的某个值,则将req作为该函数的第一个参数。
默认值是一个使用uid安全库生成ID的函数。
注意:要小心生成唯一的ID,这样会话就不会冲突。
跳到重点的来讲:
req.session
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. For example below is a user-specific view counter:
要存储或访问会话数据,只需使用request属性req。req.session(通常)将其序列化为JSON,因此嵌套对象通常是可以使用的。例如,下面是一个特定于用户的视图计数器:
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }}))// Access the session as req.sessionapp.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!') }})
Session.regenerate(callback)
To regenerate the session simply invoke the method. Once complete, a new SID and Session instance will be initialized at req.session and the callback will be invoked.
要重新生成会话,只需调用该方法。一旦完成,一个新的SID和会话实例将在req时初始化。会话和回调将被调用。
req.session.regenerate(function(err) { // will have a new session here})
Session.destroy(callback)
Destroys the session and will unset the req.session property. Once complete, the callback will be invoked.
销毁会话并取消Session.destroy属性。完成后,将调用回调。
req.session.destroy(function(err) { // cannot access session here})
Session.reload(callback)
Reloads the session data from the store and re-populates the req.session object. Once complete, the callback will be invoked.
从存储区重新加载会话数据并重新填充 req.session对象。完成后,将调用回调。
req.session.reload(function(err) { // session updated})
Session.save(callback)
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). 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.
将会话保存回存储区,用内存中的内容替换存储区中的内容(尽管存储区可能会执行其他操作——请参阅存储区的文档以了解确切行为)。
如果会话数据已被更改,则会在HTTP响应结束时自动调用此方法(尽管可以使用中间件构造函数中的各种选项更改此行为)。因此,通常不需要调用此方法。
在某些情况下,调用此方法很有用,例如重定向、长期请求或在WebSocket中。