我在Next.js 13中创建了一个网站,并有一个名为/api/users/me
的路由。在那个路由里面,我必须得到饼干来提取令牌。当我从浏览器调用路由API时,我得到了我想要的结果,但是当我试图从前端页面调用它时,它在cookie中为null
在src/api/users/me/route.js
import { NextResponse, NextRequest } from "next/server";
import { connectDB } from "@/dbConfig/dbConfig";
connectDB();
export async function GET(request) {
try {
console.log("Token is: ", request.cookies); // expect to get cookies, but null
return NextResponse.json({ msg: "success" }, { status: 200 });
} catch (error) {
return NextResponse.json(
{ msg: "can't get data", err: error.message },
{ status: 500 }
);
}
}
字符串
在src/app/profile/page.jsx中
import UserDetails from "@/components/UserDetails";
import { cookies } from "next/headers";
async function getData() {
const cookieStore = cookies();
const token = cookieStore.get("token"); // here i get the cookies
try {
console.log(token.value);
const res = await fetch(`http://localhost:3000/api/users/me`, {
headers: {
userToken: String(token.value), // try to pass it in the headers
},
});
if (!res.ok) {
throw new Error("Failed to fetch data, please try another time");
}
return res.json();
} catch (error) {
console.log("Error loading topic", error);
}
}
async function ProfilePage() {
const data = await getData();
return (
<div className="flex flex-col justify-center items-center min-h-screen">
<h1 className="font-bold text-3xl">Profile page</h1>
<p className="text-gray-600">This is the profile page</p>
<UserDetails />
</div>
);
}
export default ProfilePage;
型
1条答案
按热度按时间f45qwnt81#
您没有创建有效的API路由。API路由应该在
route.js
文件中定义。将
src/api/users/me.js
移动到src/app/api/users/me/route.js
对于cookie,请查看此文档-https://nextjs.org/docs/app/building-your-application/routing/router-handlers#dynamic-functions
字符串