Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

setHeaders 函数不能与 Set-Cookie 标头一起使用。相反,你应该使用 cookies API。

¥The setHeaders function can’t be used with the Set-Cookie header. Instead, you should use the cookies API.

在你的 load 函数中,你可以使用 cookies.get(name, options) 读取 cookie:

¥In your load functions, you can read a cookie with cookies.get(name, options):

src/routes/+page.server
export function load({ cookies }) {
	const visited = cookies.get('visited');

	return {
		visited: visited === 'true'
	};
}

要设置 cookie,请使用 cookies.set(name, value, options)。强烈建议你在设置 cookie 时明确配置 path,因为浏览器的默认行为(有点没用)是在当前路径的父级上设置 cookie。

¥To set a cookie, use cookies.set(name, value, options). It’s strongly recommended that you explicitly configure the path when setting a cookie, since browsers’ default behaviour — somewhat uselessly — is to set the cookie on the parent of the current path.

src/routes/+page.server
export function load({ cookies }) {
	const visited = cookies.get('visited');

	cookies.set('visited', 'true', { path: '/' });

	return {
		visited: visited === 'true'
	};
}

现在,如果你重新加载 iframe,Hello stranger! 将变成 Hello friend!

¥Now, if you reload the iframe, Hello stranger! becomes Hello friend!.

调用 cookies.set(name, ...) 会导致写入 Set-Cookie 标头,但它也会更新 cookie 的内部映射,这意味着在同一请求期间对 cookies.get(name) 的任何后续调用都将返回更新的值。在底层,cookies API 使用流行的 cookie 包 — 传递给 cookies.getcookies.set 的选项对应于 cookie documentation 中的 parseserialize 选项。SvelteKit 设置以下默认值以使你的 cookie 更安全:

¥Calling cookies.set(name, ...) causes a Set-Cookie header to be written, but it also updates the internal map of cookies, meaning any subsequent calls to cookies.get(name) during the same request will return the updated value. Under the hood, the cookies API uses the popular cookie package — the options passed to cookies.get and cookies.set correspond to the parse and serialize options from the cookie documentation. SvelteKit sets the following defaults to make your cookies more secure:

{
	httpOnly: true,
	secure: true,
	sameSite: 'lax'
}
上一页 下一页
1
2
3
4
5
<script>
	let { data } = $props();
</script>
 
<h1>Hello {data.visited ? 'friend' : 'stranger'}!</h1>