Cookie
使用 Bun 内置的 Cookie API 处理 HTTP 请求和响应中的 Cookie。
Bun 内置了用于处理 HTTP 请求和响应中 Cookie 的 API。BunRequest 对象提供了一个 cookies 属性,即用于读取和修改 Cookie 的 CookieMap。使用 routes 时,Bun.serve() 会自动跟踪对 request.cookies.set 的调用,并将其应用到响应中。
读取 cookies
通过 BunRequest 对象上的 cookies 属性读取来自请求的 cookies:
TypeScript
Bun.serve({
routes: {
"/profile": req => {
// 访问请求中的 cookies
const userId = req.cookies.get("user_id");
const theme = req.cookies.get("theme") || "light";
return Response.json({
userId,
theme,
message: "个人资料页",
});
},
},
});
设置 cookies
要设置 cookies,使用 BunRequest 对象中 CookieMap 的 set 方法。
TypeScript
Bun.serve({
routes: {
"/login": req => {
const cookies = req.cookies;
// 设置一个带有多个选项的 cookie
cookies.set("user_id", "12345", {
maxAge: 60 * 60 * 24 * 7, // 1 周
httpOnly: true,
secure: true,
path: "/",
});
// 添加一个主题偏好 cookie
cookies.set("theme", "dark");
// 请求中被修改的 cookies 会自动应用到响应中
return new Response("登录成功");
},
},
});
删除 cookie
要删除 cookie,使用 request.cookies(CookieMap)对象的 delete 方法:
TypeScript
Bun.serve({
routes: {
"/logout": req => {
// 删除 user_id cookie
req.cookies.delete("user_id", {
path: "/",
});
return new Response("注销成功");
},
},
});
被删除的 cookie 会作为响应中的 Set-Cookie 标头,其 Expires 属性设置为过去的日期,并且 value 为空。