Cookie

使用 Cookie 在客户端存储数据。¥Use cookies to store data on the client.

使用 H3 处理 Cookie 非常简单。有三个实用程序用于处理 Cookie:

¥Handling cookies with H3 is straightforward. There is three utilities to handle cookies:

  • setCookie 用于将 Cookie 附加到响应。
  • getCookie 用于从请求中获取 Cookie。
  • deleteCookie 用于从响应中清除 Cookie。

¥Set a Cookie

要设置 Cookie,你需要在事件处理程序中使用 setCookie

¥To set a cookie, you need to use setCookie in an event handler:

import { setCookie } from "h3";

app.use(async (event) => {
  setCookie(event, "name", "value", { maxAge: 60 * 60 * 24 * 7 });
  return "";
});

在选项中,你可以配置 cookie 标志

¥In the options, you can configure the cookie flags:

  • maxAge 用于设置 Cookie 的过期日期(以秒为单位)。
  • expires 用于设置 Date 对象中 Cookie 的过期日期。
  • path 用于设置 Cookie 的路径。
  • domain 用于设置 Cookie 的域名。
  • secure 用于设置 Cookie 的 Secure 标志。
  • httpOnly 用于设置 Cookie 的 HttpOnly 标志。
  • sameSite 用于设置 Cookie 的 SameSite 标志。
Read more in Utils.

¥Get a Cookie

要获取 Cookie,你需要在事件处理程序中使用 getCookie

¥To get a cookie, you need to use getCookie in an event handler.

import { getCookie } from "h3";

app.use(async (event) => {
  const name = getCookie(event, "name");

  // do something...

  return "";
});

如果 Cookie 存在,则返回其值;否则,返回 undefined

¥This will return the value of the cookie if it exists, or undefined otherwise.

¥Delete a Cookie

要删除 Cookie,你需要在事件处理程序中使用 deleteCookie

¥To delete a cookie, you need to use deleteCookie in an event handler:

import { deleteCookie } from "h3";

app.use(async (event) => {
  deleteCookie(event, "name");
  return "";
});

实用程序 deleteCookie 是对 setCookie 的封装器,其值设置为 ""maxAge 设置为 0

¥The utility deleteCookie is a wrapper around setCookie with the value set to "" and the maxAge set to 0.

这将从客户端清除 Cookie。

¥This will erase the cookie from the client.