Deno oak v10.5.1 context.cookies 从未设置

Deno oak v10.5.1 context.cookies never being set

当尝试在 oak 中设置 cookie 时,上下文的 cookie 属性 永远不会更改,并且即使在其文档中使用示例时也始终返回未定义的值。

app.use(async ctx => {
    try {
        const lastVisit = await ctx.cookies.get('lastVisit')
        console.log(lastVisit)
        await ctx.cookies.set('lastVisit', new Date().toISOString())
        if (lastVisit) {
            console.log(`Welcome back. You were last here at ${lastVisit}.`)
        } else {
            console.log(`Welcome, I haven't seen your before.`)
        }
    } catch (error) {
        console.error(error)
    }
})

我访问 cookie 的方式不正确吗?

这是一个基于您共享的代码的示例,它展示了如何使用 Oak 读取和设置 cookie(以及在上下文状态中存储数据)。您可以简单地复制并粘贴到 Deno Deploy 上的 playground 或项目中进行尝试:

import {
  Application,
  type Context,
  type Middleware,
  Router,
} from "https://deno.land/x/oak@v10.5.1/mod.ts";

// The shape of the state for this server app
// It can hold the last visited timestamp as a Date object
type State = {
  lastVisit?: Date | undefined;
};

const cookieMiddleWare: Middleware<
  State,
  Context<State, State>
> = async (ctx, next) => {
  // Get cookie value (if it exists)
  const lastVisit = await ctx.cookies.get("last_visit");
  // If it does, parse as a Date and set it to the context state
  if (lastVisit) ctx.state.lastVisit = new Date(lastVisit);
  // Update the cookie with the current timestamp
  await ctx.cookies.set("last_visit", new Date().toISOString());
  // Continue with next middleware
  await next();
};

// Handle visits to the root path only
const router = new Router<State>()
  .get("/", (ctx) => {
    // If the last visit date is on the state, stringify it
    // else set it to null
    const lastVisit = ctx.state.lastVisit
      ? ctx.state.lastVisit.toISOString()
      : null;

    ctx.response.body = lastVisit
      ? `Welcome back. Your last visit was: ${lastVisit}`
      : `Welcome. I haven't seen you before.`;
  });

const app = new Application<State>()
  .use(cookieMiddleWare)
  .use(router.routes())
  .use(router.allowedMethods());

app.addEventListener("listen", ({ hostname, port, secure }) => {
  console.log(`Listening at http${secure ? "s" : ""}://${hostname}:${port}/`);
});

await app.listen({ port: 8080 });