next.js 如何在下一个13应用程序目录中获取/解密令牌?

zfycwa2u  于 2023-06-05  发布在  其他
关注(0)|答案(1)|浏览(161)

如何在服务器组件中访问此Cookie,以便每个用户都有自己的userId(由middelware.ts设置)?
我试着阅读下一个文档,但我似乎无法弄清楚。不确定我是否正确地访问了它,因为“else”语句从未被触发。刷新时出现在控制台中:设置新的userId cookie { name:'userId',值:'12345' }
浏览器开发工具>应用程序> Cookie中未显示新Cookie
middleware.ts

import { NextRequest, NextResponse } from "next/server"

export function middleware(req: NextRequest) {
  if (req.nextUrl.pathname === "/") {

    if (!req.cookies.has("userId")) {
      req.cookies.set("userId", "12345")
      const userId = req.cookies.get("userId")
      console.log("set new userId cookie", userId)
    } else {
      const userId = req.cookies.get("userId")
      console.log("Existing userId:", userId)
    }
  }
  return NextResponse.next()
}

export const config = {
  matcher: "/"
}

服务器组件中的代码:

import { cookies } from "next/headers"
...
      const cookiesStore = cookies()
      const userId = cookiesStore.get("userId");
      console.log(userId)
...

上述日志“未定义”

myzjeezk

myzjeezk1#

您必须使用value字段访问器来获取cookie值。使用App dir和NextJS v13.4版本如下示例:

const cookieStore = cookies();
const userIdCookie = cookieStore.get('userId');

// ... Check if userIdCookie is defined, add some checks

const val: string = userIdCookie.value;

就是这样:)

相关问题