如何在服务器组件中访问此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)
...
上述日志“未定义”
1条答案
按热度按时间myzjeezk1#
您必须使用value字段访问器来获取cookie值。使用App dir和NextJS v13.4版本如下示例:
就是这样:)