Simple cookie-based session middleware.简单的基于cookie的会话中间件。
A user session can be stored in two main ways with cookies: on the server or on the client. 用户会话可以通过cookie以两种主要方式存储:在服务器上或在客户机上。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中的客户端上,而类似express-session的模块仅将会话标识符存储在cookie中的客户端上,并将会话数据存储在服务器上,通常存储在数据库中。
The following points can help you choose which to use:以下几点可以帮助您选择使用哪一个:
cookie-session
cookie-session
cookie-session
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 cookie-session
var cookieSession = require('cookie-session')
var express = require('express')
var app = express()
app.use(cookieSession({
name: 'session',
keys: [/* secret keys */],
// Cookie Options
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}))
Create a new cookie session middleware with the provided options. 使用提供的选项创建新的cookie会话中间件。This middleware will attach the property 该中间件将属性session
to req
, which provides an object representing the loaded session. session
附加到req
,req
,它提供一个表示已加载会话的对象。This session is either a new session if no valid session was provided in the request, or a loaded session from the request.如果请求中未提供有效会话,则此会话是新会话,或者是请求中加载的会话。
The middleware will automatically add a 如果Set-Cookie
header to the response if the contents of req.session
were altered. req.session
的内容被更改,中间件将自动向响应添加一个Set-Cookie
头。Note that no 请注意,除非会话中有内容,否则响应中不会出现Set-Cookie
header will be in the response (and thus no session created for a specific user) unless there are contents in the session, so be sure to add something to req.session
as soon as you have identifying information to store for the session.Set-Cookie
标头(因此也不会为特定用户创建会话),因此请确保在您有会话的标识信息要存储后,立即向req.session
添加内容。
Cookie session accepts these properties in the options object.Cookie会话在options对象中接受这些属性。
The name of the cookie to set, defaults to 要设置的cookie的名称默认为session
.session
。
The list of keys to use to sign & verify cookie values, or a configured Keygrip instance. 用于签名的密钥列表&;验证cookie值或已配置的Keygrip实例。Set cookies are always signed with Set cookies始终使用keys[0]
, while the other keys are valid for verification, allowing for key rotation. keys[0]
签名,而其他键对验证有效,允许键旋转。If a 如果提供了Keygrip
instance is provided, it can be used to change signature parameters like the algorithm of the signature.Keygrip
实例,则可以使用它更改签名参数,如签名的算法。
A string which will be used as single key if 如果未提供键,将用作单个keys
is not provided.keys
的字符串。
Other options are passed to 其他选项传递给cookies.get()
and cookies.set()
allowing you to control security, domain, path, and signing among other settings.cookies.get()
和cookies.set()
,允许您在其他设置中控制安全性、域、路径和签名。
The options can also contain any of the following (for the full list, see cookies module documentation:这些选项还可以包含以下任何内容(有关完整列表,请参阅cookies模块文档):
maxAge
Date.now()
for expiryDate.now()
到到期的毫秒数expires
Date
object indicating the cookie's expiration date (expires at the end of session by default).Date
对象,指示cookie的过期日期(默认情况下在会话结束时过期)。path
/
by default)./
默认)。domain
sameSite
false
by default). false
)。'strict'
, 'lax'
, 'none'
, or true
(which maps to 'strict'
).'strict'
、'lax'
、'none'
或true
(映射为'strict'
)。secure
false
by default for HTTP, true
by default for HTTPS). false
,HTTPS默认为true
)。true
and Node.js is not directly over a TLS connection, be sure to read how to setup Express behind proxies or the cookie may not ever set correctly.true
,并且Node.js不是直接通过TLS连接,请务必阅读如何在代理后设置Express,否则cookie可能无法正确设置。httpOnly
true
by default).true
)。signed
true
by default).true
)。overwrite
true
by default).true
)。Represents the session for the given request.表示给定请求的会话。
Is 如果在请求过程中更改了会话,则为true
if the session has been changed during the request.true
。
Is 如果会话是新的,则为true
if the session is new.true
。
Determine if the session has been populated with data or is empty.确定会话是否已填充数据或为空。
Represents the session options for the current request. 表示当前请求的会话选项。These options are a shallow clone of what was provided at middleware construction and can be altered to change cookie setting behavior on a per-request basis.这些选项是中间件构造中提供的内容的简单克隆,可以根据每个请求更改cookie设置行为。
To destroy a session simply set it to 要销毁会话,只需将其设置为null
:null
:
req.session = null
Since the entire contents of the session is kept in a client-side cookie, the session is "saved" by writing a cookie out in a 由于会话的全部内容都保存在客户端cookie中,因此通过在Set-Cookie
response header. Set-Cookie
响应头中写入cookie来“保存”会话。This is done automatically if there has been a change made to the session when the Node.js response headers are being written to the client and the session was not destroyed.如果在将Node.js响应头写入客户端时对会话进行了更改,并且会话未被破坏,则会自动执行此操作。
var cookieSession = require('cookie-session')
var express = require('express')
var app = express()
app.set('trust proxy', 1) // trust first proxy
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}))
app.get('/', function (req, res, next) {
// Update views
req.session.views = (req.session.views || 0) + 1
// Write response
res.end(req.session.views + ' views')
})
app.listen(3000)
var cookieSession = require('cookie-session')
var express = require('express')
var app = express()
app.set('trust proxy', 1) // trust first proxy
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}))
// This allows you to set req.session.maxAge to let certain sessions这允许您设置req.session.maxAge以允许某些会话
// have a different value than the default.具有与默认值不同的值。
app.use(function (req, res, next) {
req.sessionOptions.maxAge = req.session.maxAge || req.sessionOptions.maxAge
next()
})
// ... your logic here ...
This module does not send a 如果会话的内容没有更改,则此模块不会发送Set-Cookie
header if the contents of the session have not changed. Set-Cookie
标头。This means that to extend the expiration of a session in the user's browser (in response to user activity, for example) some kind of modification to the session needs be made.这意味着要延长用户浏览器中会话的到期时间(例如,响应用户活动),需要对会话进行某种修改。
var cookieSession = require('cookie-session')
var express = require('express')
var app = express()
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}))
// Update a value in the cookie so that the set-cookie will be sent.更新cookie中的值,以便发送设置的cookie。
// Only changes every minute so that it's not sent with every request.每分钟只更改一次,这样就不会随每个请求一起发送。
app.use(function (req, res, next) {
req.session.nowInMinutes = Math.floor(Date.now() / 60e3)
next()
})
// ... your logic here ...
This example shows creating a custom 此示例显示如何创建自定义Keygrip
instance as the keys
option to provide keys and additional signature configuration.Keygrip
实例作为keys
选项,以提供密钥和其他签名配置。
var cookieSession = require('cookie-session')
var express = require('express')
var Keygrip = require('keygrip')
var app = express()
app.use(cookieSession({
name: 'session',
keys: new Keygrip(['key1', 'key2'], 'SHA384', 'base64')
}))
// ... your logic here ...
Because the entire session object is encoded and stored in a cookie, it is possible to exceed the maxium cookie size limits on different browsers. 因为整个会话对象都编码并存储在cookie中,所以在不同的浏览器上可能会超过最大cookie大小限制。The RFC6265 specification recommends that a browser SHOULD allowRFC6265规范建议浏览器应允许
At least 4096 bytes per cookie (as measured by the sum of the length of the cookie's name, value, and attributes)每个cookie至少4096字节(通过cookie的名称、值和属性的长度之和来衡量)
In practice this limit differs slightly across browsers. 实际上,不同浏览器的限制略有不同。See a list of browser limits here. 请参见此处的浏览器限制列表。As a rule of thumb don't exceed 4093 bytes per domain.根据经验,每个域不超过4093字节。
If your session object is large enough to exceed a browser limit when encoded, in most cases the browser will refuse to store the cookie. 如果会话对象足够大,编码时超出浏览器限制,则在大多数情况下,浏览器将拒绝存储cookie。This will cause the following requests from the browser to either a) not have any session information or b) use old session information that was small enough to not exceed the cookie limit.这将导致以下来自浏览器的请求a)没有任何会话信息,或b)使用小到不超过cookie限制的旧会话信息。
If you find your session object is hitting these limits, it is best to consider if data in your session should be loaded from a database on the server instead of transmitted to/from the browser with every request. 如果发现会话对象正在命中这些限制,最好考虑会话中的数据是否应该从服务器上的数据库加载,而不是用每个请求发送到浏览器。Or move to an alternative session strategy或者转向另一种会话策略