-
카테고리
-
세부 분야
프론트엔드
-
해결 여부
미해결
dynamic page에서의 API 호출, 코드상 질문 드립니다.
24.01.08 01:29 작성 조회수 107
0
export default function Page({ params }: { params: { postId: number } }){ }
다음과 같이 app/(Logined)/home/Post/[postId]/page.tsx 에서 params를 불러왔을 때,
prisma와 REST API를 이용하여 데이터를 요청하고 가져오는 것을 할 때,
1.page가 params.postId를 이용하여 NextRequest를 요청하면
2. route.ts가 해당 Request를 받고 prisma를 통해 쿼리를 한 뒤,
3. NextResponse로 page에 답장하는 형식을 구현하고자 합니다.
근데 해당 구현에 대해서, 공식 문서에서 제가 해당 내용을 잘 응용하지 못하는 것인지,
GET http://localhost:3000/api/post/4 500 (Internal Server Error)에러만 발생하고 'post'를 불러오지 못하고 있습니다. 이에 눈에 띄는 코드 오류는 없는지 핵심 부분이 빠진 것은 없는지 질문 드립니다.
// app/(Logined)/home/Post/[postId]/page.tsx
"use client";
import React, { useEffect, useState } from "react";
import { PostType } from "@/app/(Logined)/_components/TYPE_post";
export default function Page({ params }: { params: { postId: number } }) {
const [post, setPost] = useState<PostType | null>(null);
const postid = params.postId;
useEffect(() => {
const fetchPostData = async () => {
try {
const response = await fetch(`/api/post/${postid}`);
if (response.ok) {
const postData: PostType = await response.json();
setPost(postData);
} else {
console.error("Error fetching post");
}
} catch (error) {
console.error("Error:", error);
}
};
if (params.postId) {
fetchPostData();
}
}, [params.postId]);
if (!post) {
return <div>Loading...</div>;
}
return (
<div>
<h1>Post Details</h1>
<p>Description: {post.description}</p>
<p>Event Date: {post.eventDate.toString()}</p>
<p>Deadline: {post.deadline.toString()}</p>
</div>
);
}
// pages/api/post/[postId]/route.ts
import prisma from "@/app/lib/prisma";
import { NextResponse, NextRequest } from "next/server";
export async function GET(req: NextRequest) {
const postId = parseInt(req.nextUrl.searchParams.get("postId") || "0");
if (!postId) {
return new NextResponse(JSON.stringify({ message: "Invalid post ID" }), {
status: 400,
});
}
try {
const post = await prisma.post.findUnique({
where: { id: postId },
select: {
description: true,
eventDate: true,
deadline: true,
},
});
if (post) {
return new NextResponse(JSON.stringify(post));
} else {
return new NextResponse(JSON.stringify({ message: "Post not found" }), {
status: 404,
});
}
} catch (error) {
console.error("Error fetching post:", error);
return new NextResponse(
JSON.stringify({ message: "Error fetching post" }),
{ status: 500 }
);
}
}
답변을 작성해보세요.
0
답변 1