Deno Oak v10.5.1 Context.Cookies从未设置

发布于 2025-01-26 04:56:51 字数 605 浏览 3 评论 0原文

尝试在橡木中设置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吗?

When attempting to set cookies in oak, the cookies property of the context is never changed and the value is always returned undefined even when using the example in their docs.

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

Am I not accessing the cookies the correct way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够钟 2025-02-02 04:56:51

这是基于您共享的代码的示例,该示例显示了如何使用OAK读取和设置cookie(并将数据存储在上下文状态)。您可以只需将 +粘贴复制到

import {
  Application,
  type Context,
  type Middleware,
  Router,
} from "https://deno.land/x/[email protected]/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 });

Here's an example based on the code you shared which shows how to read and set a cookie (and also store data in the context's state) using Oak. You can simply copy + paste into a playground or project on Deno Deploy to try it:

import {
  Application,
  type Context,
  type Middleware,
  Router,
} from "https://deno.land/x/[email protected]/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 });

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文