【问题标题】:SvelteKit does not set cookie returned from GET endpointSvelteKit 不设置从 GET 端点返回的 cookie
【发布时间】:2022-01-29 09:04:00
【问题描述】:

我正在重新编写我的问题和代码示例,以便于理解。

当我调用这个 PUT 端点时,cookie 设置正确。

export const put: RequestHandler<Locals> = async (event) => {
  const userInfo = {
    refresh_token: Math.random().toString(),
  };

  const json = JSON.stringify(userInfo);

  const jwt = cookie.serialize("jwt", json, {
    httpOnly: true,
    path: "/",
  });

  const headers = {
    "Set-Cookie": [jwt],
  };

  return {
    status: 200,
    headers,
    body: {},
  };
};

当我调用这个 GET 端点时,cookie 没有设置。

export const get: RequestHandler<Locals> = async (event) => {
  const userInfo = {
    refresh_token: Math.random().toString(),
  };

  const json = JSON.stringify(userInfo);

  const jwt = cookie.serialize("jwt", json, {
    httpOnly: true,
    path: "/",
  });

  const headers = {
    "Set-Cookie": [jwt],
  };

  return {
    status: 200,
    headers,
    body: {},
  };
};

这是发送到 fetch 的选项,其中方法等于每种情况下的“GET”或“PUT”:

  const opts: RequestInit = {
    method,
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
    },
  };

  if (data) {
    opts.body = JSON.stringify(data);
  }

【问题讨论】:

  • 您可以尝试在handle 挂钩中设置cookie 吗? kit.svelte.dev/docs#hooks-handleresponse.headers.append('set-cookie', jwt)
  • 但是我如何将 JWT 从端点发送回钩子句柄?像这样尝试但没有成功,PUT 有效,GET 无效。 const headers = { refresh_token: JSON.stringify(userInfo.refresh_token), "Set-Cookie": [jwt], };
  • 我使用来自端点的 event.locals 发送了 JWT,它工作了。 Cookie 设置正确@kenset
  • 测试了一切,一切正常。谢谢@kenset
  • 很高兴听到这个消息!我会写下来给未来的读者。

标签: cookies jwt sveltekit


【解决方案1】:

handle 钩子中设置cookie,可以在一个地方为两个端点设置它。见https://kit.svelte.dev/docs#hooks-handle

从您的端点通过event.locals 对象将JWT 传递给handle 方法。

例如,

/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
    const response = await resolve(event);
    response.headers.append('set-cookie', event.locals.jwt);
    return response;
}

【讨论】:

  • 刚注意到有些东西还是坏了。浏览整个网站完美无缺,cookie 设置正确。但是当我点击“刷新”(F5,Ctrl + r)时,cookie 没有设置,它仍然与前一个相同。我可以从“句柄”函数返回的响应中看到它正在尝试将 cookie 设置为新的。
  • 您介意提出一个新的问题吗?这感觉像是一个不同的问题。在那个问题中,我很想知道您的 handle 方法是什么样的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2012-02-11
  • 2020-06-04
  • 2021-08-10
  • 2020-11-10
相关资源
最近更新 更多