# res.cookie

将 cookie name 设置为 value

# 概要

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 的路径。默认为 "/"。
secure 布尔值 将 cookie 标记为仅与 HTTPS 一起使用。
signed 布尔值 指示是否应该对 cookie 进行签名。
sameSite 布尔值或字符串 "SameSite" Set-Cookie 属性的值。

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 })

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.signedCookies 对象访问此值。

Last Updated: 3/22/2023, 7:27:28 PM