无法使用 Fastify 后端在 Next 客户端上设置 cookie。
我有一个 Next.JS 客户端和一个 Fastify 后端。我做了这个简单的端点来设置 httpOnly cookie
server.get("/set-cookie", async (req, reply) => {
reply.setCookie("test-cookie", "this is a test", {
path: "/",
httpOnly: true,
secure: false,
sameSite: "lax",
domain: "localhost",
});
reply.send({ message: "cookie set succesfuly" });
});
这在 Postman 上运行良好,但在我的客户端上不起作用。 这是我的 Nextjs 组件,用于测试端点:
import { cookies } from "next/headers";
async function getCookie() {
const res = await fetch("http://localhost:8080/set-cookie", {
credentials: "include",
});
if (res.ok) console.log(cookies().getAll());
}
export default async function Page() {
await getCookie();
return <>test</>;
}
我的“网络”选项卡中也没有任何 Set-Cookie 标头。
您在 Next.js 组件中处理响应的方式似乎可能存在问题。 cookies().getAll() 方法不是从 Next.js 中的响应访问 cookie 的正确方法。相反,您应该使用 response.headers 对象来访问 Set-Cookie 标头。
async function getCookie() {
const res = await fetch("http://localhost:8080/set-cookie", {
credentials: "include",
});
if (res.ok) {
const setCookieHeader = res.headers.get("Set-Cookie");
console.log(setCookieHeader);
}
}