EdgeOne Logo
Documentation
请选择
请选择
Overview
Menu

设置 Cookie

该示例使用 Cookies 做访问计数,当浏览器访问边缘函数服务时,请求计数加 1。

示例代码

// cookie 名称
const COOKIE_NAME = 'count';

async function handleRequest(request) {
// 获取当前请求的 Cookies,并解析为对象
const cookies = new Cookies(request.headers.get('cookie'));
const cookieCount = cookies.get(COOKIE_NAME);
// 计数累加
const count = Number(cookieCount && cookieCount.value || 0) + 1;
// 更新 cookie 的计数
cookies.set(COOKIE_NAME, String(count));

const response = new Response(`The count is: ${count}`);
// 设置响应 cookies
response.headers.set('Set-Cookie', getSetCookie(cookies.get(COOKIE_NAME)));
return response;
}

// 拼接 Set-Cookie
function getSetCookie(cookie) {
const cookieArr = [
`${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`,
];

const key2name = {
expires: 'Expires',
max_age: 'Max-Age',
domain: 'Domain',
path: 'Path',
secure: 'Secure',
httponly: 'HttpOnly',
samesite: 'SameSite',
};

Object.keys(key2name).forEach(key => {
if (cookie[key]) {
cookieArr.push(`${key2name[key]}=${cookie[key]}`);
}
});

return cookieArr.join('; ');
}

addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});

示例预览

在浏览器地址栏中输入匹配到边缘函数触发规则的 URL,即可预览到示例效果。




相关参考