res.cookie(name, value [, options])

中英双语

将 cookie name 设置为 valuevalue 参数可以是字符串或转换为 JSON 的对象。

options 参数是一个可以具有以下属性的对象。

属性类型描述
domain字符串cookie 的域名。默认为应用的域名。
encode函数用于 cookie 值编码的同步函数。默认为 encodeURIComponent
expires日期格林威治标准时间 cookie 的到期日期。如果未指定或设置为 0,则创建会话 cookie。
httpOnly布尔值将 cookie 标记为只能由 Web 服务器访问。
maxAge数字方便的选项,用于设置相对于当前时间的到期时间(以毫秒为单位)。
path字符串cookie 的路径。默认为 "/"。
priority字符串"Priority" Set-Cookie 属性的值。
secure布尔值将 cookie 标记为仅与 HTTPS 一起使用。
signed布尔值指示是否应该对 cookie 进行签名。
sameSite布尔值或字符串"SameSite" Set-Cookie 属性的值。更多信息请参见 https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00#section-4.1.1

res.cookie() 所做的只是使用提供的选项设置 HTTP Set-Cookie 标头。任何未指定的选项默认为 RFC 6265 中规定的值。

例如:

res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true })
res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })

您可以通过多次调用 res.cookie 在单个响应中设置多个 cookie,例如:

res
  .status(201)
  .cookie('access_token', 'Bearer ' + token, {
    expires: new Date(Date.now() + 8 * 3600000) // cookie will be removed after 8 hours
  })
  .cookie('test', 'test')
  .redirect(301, '/admin')

encode 选项允许您选择用于 cookie 值编码的函数。不支持异步函数。

示例用例:您需要为组织中的另一个站点设置域范围的 cookie。此其他站点(不受您的管理控制)不使用 URI 编码的 cookie 值。

// Default encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com' })
// Result: 'some_cross_domain_cookie=http%3A%2F%2Fmysubdomain.example.com; Domain=example.com; Path=/'

// Custom encoding
res.cookie('some_cross_domain_cookie', 'http://mysubdomain.example.com', { domain: 'example.com', encode: String })
// Result: 'some_cross_domain_cookie=http://mysubdomain.example.com; Domain=example.com; Path=/;'

maxAge 选项是一个方便的选项,用于设置 "expires" 相对于当前时间(以毫秒为单位)。以下等效于上面的第二个示例。

res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })

您可以将对象作为 value 参数传递;然后将其序列化为 JSON 并由 bodyParser() 中间件解析。

res.cookie('cart', { items: [1, 2, 3] })
res.cookie('cart', { items: [1, 2, 3] }, { maxAge: 900000 })

使用 cookie-parser 中间件时,此方法还支持签名 cookie。只需将 signed 选项设置为 true。然后 res.cookie() 将使用传递给 cookieParser(secret) 的秘密对值进行签名。

res.cookie('name', 'tobi', { signed: true })

稍后您可以通过 req.signedCookie 对象访问此值。