【问题标题】:NextJS middleware cookies issueNextJS 中间件 cookie 问题
【发布时间】:2023-02-25 10:16:21
【问题描述】:

我想在访问之前检查用户是否在 cookie 中有一个有效的令牌/api我的 NextJS 应用程序上的路由,所以我创建了一个中间件来检查它。 不知何故,我无法从我的中间件中的 req.cookies 中提取值...我遵循了 NextJS 官方文档 (https://nextjs.org/docs/advanced-features/middleware)。首先 TypeScript 已经抛出错误:错误 [TypeError]: request.cookies.getAll 不是函数并且类型“字符串”上不存在属性“值”。您指的是“valueOf”吗?ts(2551)

export function middleware(request: NextRequest) {
  const cookie = request.cookies.get("token")?.value;
  console.log(cookie);

  const allCookies = request.cookies.getAll();
  console.log(allCookies);

  const response = NextResponse.next();
  return response;
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: "/api/:path*",
};

【问题讨论】:

  • 我有一个关于 getAll 的类似情况的错误,它在 next@12.3.1 的 req.cookies 上不存在。您是否尝试过检查 cookie 对象上有哪些可用属性?
  • 您还可以向我们展示您对该文件的导入,命名为 NextRequest 导入吗?
  • 这是标准的 NextJS 请求类型。从“下一个/服务器”导入类型{NextRequest};

标签: node.js next.js middleware


【解决方案1】:

看起来文档或类型不正确?

12.2.x 中 NextCookies 的类型:

export declare class NextCookies extends Cookies {
    response: Request | Response;
    constructor(response: Request | Response);
    get: (key: string) => string | undefined;
    getWithOptions: (key: string) => GetWithOptionsOutput;
    set: (key: string, value: unknown, options?: CookieSerializeOptions | undefined) => this;
    delete: (key: string, options?: CookieSerializeOptions) => boolean;
    clear: (options?: CookieSerializeOptions) => void;
}

您会注意到未定义方法 getAll。对于它的价值,我在 13.2.x 中不再收到此错误

【讨论】:

    【解决方案2】:

    您无法在中间件中读取 cookie 值。您只能在服务器端读取 cookie 值,例如获取服务器端属性

    【讨论】:

    猜你喜欢
    • 2020-08-20
    • 2021-05-12
    • 2021-10-27
    • 1970-01-01
    • 2021-03-11
    • 2021-11-13
    • 2022-11-02
    • 2021-10-08
    • 1970-01-01
    相关资源
    最近更新 更多