Cookie
使用 H3 处理 Cookie 非常简单。有三个实用程序用于处理 Cookie:
¥Handling cookies with H3 is straightforward. There is three utilities to handle cookies:
setCookie用于将 Cookie 附加到响应。getCookie用于从请求中获取 Cookie。deleteCookie用于从响应中清除 Cookie。
设置 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标志。
获取 Cookie
¥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.
删除 Cookie
¥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.