收录了这篇文章
cookie-parser 是一个用于解析和处理 HTTP Cookie 的 Node.js 中间件,经常被用在 Express 应用中。它可以帮助你轻松地访问、创建或修改 cookies。
要在 Express 应用中使用 cookie-parser,你需要先安装这个包。你可以通过 npm(Node Package Manager)来安装它:
npm install cookie-parser
然后,在你的 Express 应用中设置中间件。下面是一个简单的例子说明如何使用 cookie-parser:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
// 使用 cookie-parser 中间件
app.use(cookieParser());
// 设置一个 cookie
app.get('/set-cookie', (req, res) => {
res.cookie('testCookie', 'testValue', { maxAge: 60 * 1000 }); // 设置一个名为 testCookie 的 cookie,有效期为 60 秒
res.send('Cookie has been set!');
});
// 获取并打印 cookie
app.get('/get-cookie', (req, res) => {
if (req.cookies.testCookie) {
res.send(`The value of the cookie is: ${req.cookies.testCookie}`);
} else {
res.send('No cookie found.');
}
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
在这个示例中,我们首先引入了 express 和 cookie-parser 模块,并使用 cookie-parser() 函数作为中间件。接着,我们定义了两个路由处理函数:
- /set-cookie 路由用来设置一个名为 testCookie 的 cookie。
- /get-cookie 路由用来获取该 cookie 并显示其值。
请注意,res.cookie() 方法用于设置 cookie,而 req.cookies 属性则可以让你访问客户端发送的 cookies。
如果你需要更复杂的 cookie 处理功能,例如签名、安全选项等,cookie-parser 也提供了这些功能。你可以查看文档以了解更多信息。
详细介绍
cookieParser(secret,options)
使用给定的 secret 和 options 创建一个新的 cookie 解析器中间件函数。
- secret用于对cookie进行签名的字符串或数组。这是可选的,如果不指定,将不会解析已签名的Cookie。如果提供了字符串,则将其用作密码。如果提供了数组,则会尝试按顺序对每个机密进行cookie取消签名。
- options 是一个对象,作为第二个选项传递给 cookie.parse。有关更多信息,请参阅cookie。
解码函数,以解码cookie的值
中间件将解析请求中的Cookie标头,并将cookie数据作为属性req.cookies公开,如果提供了秘密,则作为属性req.signedCookies公开。这些属性是cookie名称到cookie值的名称值对。
当提供 secret 时,此模块将对任何已签名的 cookie 值进行取消签名和验证,并将这些名称值对从 req.cookies 移动到 req.signedCookies 中。已签名的cookie是指具有以s:为前缀的值的cookie。签名验证失败的签名cookie将具有false值,而不是篡改值。
此外,该模块支持特殊的“JSON cookies”。这些是值前缀为j:的cookie。当遇到这些值时,该值将作为JSON.parse的结果公开。如果解析失败,则保留原始值。
cookieParser.JSONCookie(str)
将cookie值解析为JSON cookie。如果是一个JSON cookie,它将返回解析后的JSON值,否则,它将返回传递的值。
cookieParser.JSONCookie(Cookie)
给定一个对象,这将遍历键并在每个值上调用JSONCookie,用解析的值替换原始值。这将返回与传入的对象相同的对象。
cookieParser.signedCookie(str,secret)
将cookie值解析为已签名的cookie。如果这是一个有符号的cookie并且签名有效,这将返回解析后的无符号值。如果值没有签名,则返回原始值。如果值已签名,但签名无法验证,则返回false。
secret 参数可以是数组或字符串。如果提供了字符串,则将其用作 secret。如果提供了数组,则会尝试按顺序对每个机密进行cookie取消签名。
cookieParser.signedCookie(Cookie,secret)
给定一个对象,这将遍历键并检查是否有任何值是有符号的cookie。如果它是一个签名的cookie并且签名有效,则将从对象中删除密钥并将其添加到返回的新对象中。
secret 参数可以是数组或字符串。如果提供了字符串,则将其用作 secret。如果提供了数组,则将尝试按顺序对每个机密进行cookie取消签名。
Option 参数详解
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.
encode
Specifies a function that will be used to encode a cookie's value. Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode a value into a string suited for a cookie's value.
The default function is the global encodeURIComponent, which will encode a JavaScript string into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.
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.
note the cookie storage model specification states that if both expires and maxAge are set, then maxAge takes precedence, but it is possible not all clients by obey this, so if both are set, they should point to the same date and time.
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 not set.
note be careful when setting this to true, as compliant clients will not allow client-side JavaScript to see the cookie in document.cookie.
maxAge
Specifies the number (in seconds) to be the value for the Max-Age Set-Cookie attribute. The given number will be converted to an integer by rounding down. By default, no maximum age is set.
note the cookie storage model specification states that if both expires and maxAge are set, then maxAge takes precedence, but it is possible not all clients by obey this, so if both are set, they should point to the same date and time.
partitioned
Specifies the boolean value for the Partitioned Set-Cookie attribute. When truthy, the Partitioned attribute is set, otherwise it is not. By default, the Partitioned attribute is not set.
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.
path
Specifies the value for the Path Set-Cookie attribute. By default, the path is considered the "default path".
priority
Specifies the string to be the value for the Priority Set-Cookie attribute.
- 'low' will set the Priority attribute to Low.
- 'medium' will set the Priority attribute to Medium, the default priority when not set.
- 'high' will set the Priority attribute to High.
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.
sameSite
Specifies the boolean or string to be the value for the SameSite Set-Cookie attribute.
- true will set the SameSite attribute to Strict for strict same site enforcement.
- false will not set the SameSite attribute.
- '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.
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.
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.
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.
npm包地址:
https://www.npmjs.com/package/cookie-parser
https://www.npmjs.com/package/cookie
修改时间 2024-09-29