Svelte基础
Svelte高阶
上下文API
特殊元素
接下来
SvelteKit基础
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
上个练习提到的setHeaders
可不能用于设置Set-Cookie
. SvelteKit特意提供了更简单易用的API用于读写cookies
🍪
在load
函数中读取cookie可以使用cookies.get(name, options)
:
The
setHeaders
function can’t be used with theSet-Cookie
header. Instead, you should use thecookies
API. In yourload
functions, you can read a cookie withcookies.get(name, options)
:
export function load({ cookies }) {
const visited = cookies.get('visited');
return {
visited: visited === 'true'
};
}
设置Cookie可以使用cookies.set(name, value, options)
. 强烈建议设置Cookie时指定path
, 因为如果不指定有些浏览器会使用当前路径的父目录做为path
,这可能不是你想要的。
To set a cookie, use
cookies.set(name, value, options)
. It’s strongly recommended that you explicitly configure thepath
when setting a cookie, since browsers’ default behaviour — somewhat uselessly — is to set the cookie on the parent of the current path.
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!
becomesHello friend!
.
小主是不是也好奇为什么就不能直接用setHeaders
通过设置Set-Cookie
操作Cookies
呢?
主要是当使用cookies.set(name, ...)
不但会通过Set-Cookie
头信息设置Cookie值, 还会修改内部的Map,这样同一个请求内调用cookies.get(name)
也会返回最新的值,另外SvelteKit还会默认添加以下配置确保cookies
更安全:
Calling
cookies.set(name, ...)
causes aSet-Cookie
header to be written, but it also updates the internal map of cookies, meaning any subsequent calls tocookies.get(name)
during the same request will return the updated value. Under the hood, thecookies
API uses the popularcookie
package — the options passed tocookies.get
andcookies.set
correspond to theparse
andserialize
options from thecookie
documentation. SvelteKit sets the following defaults to make your cookies more secure:
{
httpOnly: true,
secure: true,
sameSite: 'lax'
}
<script>
let { data } = $props();
</script>
<h1>Hello {data.visited ? 'friend' : 'stranger'}!</h1>