【发布时间】:2022-11-02 10:46:09
【问题描述】:
我对 SvelteKit 有点陌生,我正在尝试将 cookie(特别是 JWT 令牌)从路由保存到服务器端的另一条路由(使用 +page.server.ts 和 +layout.server.ts)
这是我目前编码的:
// /account/sign-in/+page.server.ts
import { invalid, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
// ... other imports ...
export const actions: Actions = {
default: async ({ request, cookies }) => {
// conditionals to check
console.log("cookie before creation", cookies.get("auth")); // undefined
cookies.set("auth", "abc", { path: "/", maxAge: 60 * 60 * 24 * 365, httpOnly: true }); // Creates the cookie
console.log("cookie after creation", cookies.get("auth")); // "abc"
throw redirect(302, '/client/app'); // Redirect to /client/app
})
}
// /client/+layout.server.ts
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ cookies }) => {
const jwt = cookies.get('auth');
console.log("layout token", jwt); // undefined -- I expected: "abc"
}
【问题讨论】:
-
建议检查开发工具。响应标头应该告诉您是否包含
set-cookie,并且通常还有一些方法可以检查已保存的 cookie。 -
(对我来说,与此类似的代码可以按预期工作。)