Sveltekit 新创建的 cookie 未显示在 hook 的句柄函数中

Sveltekit newly created cookie is not showing in the hook's handle function

总结

一旦 set-cookie header 在响应中发送,它需要另一个请求,然后 cookie 在 handle() 函数中可见 hooks.ts 文件.

例子

  1. 用户将用户名和密码发布到登录端点;
  2. Enpoint 响应设置 access_token cookie header;
  3. 用户应该被重定向到受保护的页面。 (失败

It fails because auth guard checks if the cookie exists, but it can't be seen from a code side at this point, only in the browser end.

  1. 刷新页面

  2. 用户现在可以被重定向到受保护的页面。

Minimal reproduction

它具有虚拟 login/logout 功能和受保护的用户配置文件。还有服务器端控制台日志显示 cookie lags 在挂钩中被识别。

如评论中所述,您的服务器 returns HTTP 状态代码 200 在登录后不会重定向客户端。由于状态代码,浏览器假定它已经到达最终目的地。

在这种情况下,最佳做法是使用状态代码 302:Wikipedia

已修改 /src/routes/auth/login.ts

import * as cookie from 'cookie';

export const post = (request) => {
    return {
        status: 302,
        headers: {
            location: '/',
            'set-cookie': `${cookie.serialize('token', 'VALUE_OF_THE_COOKIE'}; path=/; HttpOnly`
        }
    }
};

export const del = (request) => {
    return {
        status: 302,
        headers: {
            location: '/',
            'set-cookie': `${cookie.serialize('token', ''}; path=/; HttpOnly; maxAge: 0`
        }
    }
};