import { getAuthSession } from "@/lib/auth";
import { db } from "@/lib/db";
export async function GET(req: Request) {
try {
// Get the user session using NextAuth.js getAuthSession function
const session = await getAuthSession();
if (!session?.user) {
// User is not logged in, return an error response
return new Response("User is not logged in", {
status: 401, // Unauthorized
});
}
// Retrieve user ID from the session object
const userId = session.user.id;
// Fetch goals associated with the user ID
const goals = await db.goal.findMany({
where: {
userId: userId,
},
});
return new Response(JSON.stringify(goals), {
status: 200,
});
} catch (error) {
// Handle any other errors that occur during the request
console.error(error);
return new Response("Internal Server Error", {
status: 500,
});
}
}
如果我在浏览器中访问此代码http://localhost:3000/api/getGoal,它会返回 401 消息,其中用户未登录,如果我未登录,它会返回 json 如果我已登录。
但是,如果我随后尝试在我的 page.tsx 中获取此 API:
import ProgressBar from '@/components/ProgressBar';
async function getData() {
const data = await fetch('http://localhost:3000/api/goal')
console.log(data.status)
if (data.status !== 200) {
throw new Error(data.statusText)
}
return data.json()
}
export default async function Home(){
const goals = await getData()
return (
<div className='flex justify-center items-center'>
<ProgressBar goals={goals} />
</div>
);
};
如果我console.log
data.status
,它总是返回状态代码200并且总是显示数据。 我想我在这里遗漏了一些东西,但我似乎无法理解它。 再说一次,我对 Nextjs 和 React 总体来说还很陌生。我尝试过不同类型的 catch 子句。我试过问chatgpt。我尝试四处寻找教程。 我希望它仅在用户登录(有会话)时显示数据。
nextjs 文档中提到的 NextResponse。
import { NextResponse } from "next/server";
export async function GET(req: Request) {
try {
// ... you code
const goals = {};
return NextResponse.json(goals, {
status: 200,
});
} catch (error) {
// Handle any other errors that occur during the request
console.error(error);
return NextResponse.json({"error": "Internal Server Error"}, {
status: 500,
});
}
}