【问题标题】:Cookies aren't saving between routes in Svelte KitCookie 不会在 Svelte Kit 中的路线之间保存
【发布时间】: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。
  • (对我来说,与此类似的代码可以按预期工作。)

标签: cookies sveltekit


【解决方案1】:

上面的代码在注释掉我的一些其他代码之后工作,并将其放在我的条件检查之前,然后它显示在浏览器中,然后恢复我的代码按预期工作。

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2020-06-29
    • 2021-03-24
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多