推荐答案
// www.javascriptcn.com code example
const fastify = require('fastify')({ logger: true });
// 注册 fastify-cookie 插件
fastify.register(require('fastify-cookie'));
// 设置 Cookie
fastify.get('/set-cookie', (request, reply) => {
reply.setCookie('username', 'john_doe', {
domain: 'example.com',
path: '/',
secure: true,
httpOnly: true,
sameSite: 'lax'
});
return { message: 'Cookie has been set' };
});
// 获取 Cookie
fastify.get('/get-cookie', (request, reply) => {
const username = request.cookies.username;
return { username };
});
// 删除 Cookie
fastify.get('/delete-cookie', (request, reply) => {
reply.clearCookie('username');
return { message: 'Cookie has been deleted' };
});
// 启动服务器
fastify.listen(3000, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info('Server is running on http://localhost:3000');
});本题详细解读
1. 注册 fastify-cookie 插件
在使用 fastify-cookie 插件之前,首先需要通过 fastify.register() 方法将其注册到 Fastify 实例中。这样,Fastify 就能够处理与 Cookie 相关的操作。
fastify.register(require('fastify-cookie'));2. 设置 Cookie
通过 reply.setCookie() 方法可以设置一个 Cookie。该方法接受三个参数:
- name: Cookie 的名称。
- value: Cookie 的值。
- options: 可选的配置项,如
domain、path、secure、httpOnly和sameSite等。
reply.setCookie('username', 'john_doe', {
domain: 'example.com',
path: '/',
secure: true,
httpOnly: true,
sameSite: 'lax'
});3. 获取 Cookie
通过 request.cookies 对象可以获取客户端发送的 Cookie。你可以通过 Cookie 的名称来访问其值。
const username = request.cookies.username;
4. 删除 Cookie
通过 reply.clearCookie() 方法可以删除一个 Cookie。该方法接受 Cookie 的名称作为参数。
reply.clearCookie('username');5. 启动服务器
最后,通过 fastify.listen() 方法启动服务器,监听指定的端口。
fastify.listen(3000, (err) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info('Server is running on http://localhost:3000');
});通过以上步骤,你可以在 Fastify 中使用 fastify-cookie 插件来处理 Cookie 的设置、获取和删除操作。