SvelteKit 不设置从 GET 端点返回的 cookie

SvelteKit does not set cookie returned from GET endpoint

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

当我调用此 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: {},
  };
};

这是发送到提取的选项,其中每个案例的方法等于“PUT”的“GET”:

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

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

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;
}