2 ๊ธ ๋ณด์ - 1 ์์ 2 ๊น์ง (์ด 2 ์ค์์)
-
๊ธ์ด์ด๊ธ
-
2024๋ 4์ 15์ผ 18:59 #120382

Byeory์ฐธ๊ฐ์import { connectDB } from "@/util/database"; import { ObjectId } from "mongodb"; import Comment from "./Comment"; import { authOptions } from "@/pages/api/auth/[...nextauth]"; import { getServerSession } from "next-auth"; import { notFound } from "next/navigation";export default async function Detail(props) { try { // ID ์ ํจ์ฑ ๊ฒ์ฌ if (!ObjectId.isValid(props.params.id)) { return ( <div> ์ฌ๋ฐ๋ฅธ ํ์์ ์์ฒญ๊ฐ์ด ์๋๋๋ค. 24๊ธ์์ 16์ง์๋ฅผ ์ ๋ ฅํด์ฃผ์ธ์. </div> ); }// ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฐ๊ฒฐ ๋ฐ ๋ฌธ์ ์กฐํ const db = (await connectDB).db("my_mongo_db"); const result = await db.collection("post").findOne({ _id: new ObjectId(props.params.id), });// ๋ฌธ์๊ฐ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์๋ ๊ฒฝ์ฐ if (result == null) { return notFound(); } else { // ๋ก๊ทธ์ธ ์ธ์ ๊ฐ์ ธ์ค๊ธฐ const loginSession = await getServerSession(authOptions); let sessionData = loginSession;// ๋ก๊ทธ์ธ ์ธ์ ํ์ธ ๋ฐ OAuth ์ฌ์ฉ์ ์ ๋ณด ์ฒ๋ฆฌ if (!loginSession || !loginSession.user._id) { const OAuthAccounts = (await connectDB).db("my_mongo_db"); const OAuthResult = await OAuthAccounts.collection("users").findOne({ email: loginSession.user.email, });if (OAuthResult) { sessionData = { ...loginSession, user: { _id: OAuthResult._id.toString(), name: OAuthResult.name || loginSession.user.name, email: OAuthResult.email, }, }; } }// ์ฑ๊ณต์ ์ผ๋ก ๋ฌธ์๋ฅผ ์ฐพ์ ๊ฒฝ์ฐ, ์์ธ ํ์ด์ง ๋ ๋๋ง return ( <div> <h4>์์ธํ์ด์ง</h4> <h4>{result.title}</h4> <p>{result.content}</p> <Comment parentId={result._id.toString()} loginSession={sessionData} /> </div> ); } } catch (error) { // ์๋ฌ ์ฒ๋ฆฌ console.error("Error fetching post details:", error); return <div>์๋ฒ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค.</div>; } }์ค๊ฐ์ ๋ง๋ฌ๋ ์ ํจ์ฑ ๊ฒ์ฆ๋ ์ถ๊ฐํ๊ณ try-catch ๊ตฌ๋ฌธ์ ๋ฃ์ด์ ์๋ฌ์ฒ๋ฆฌ๋ ๊ฐํํ์๋๋ฐ์
notFound() ํจ์๋ฅผ ํตํด์
export default function Loading(){ return <h4>404 ์๋ฌ์ ๊ทธ๊ฑด ์๋ ํ์ด์ง์ธ๋ฐ์</h4> }์ด์ ๊ฐ์ ํ์ด์ง๊ฐ ๋์์ผํ๋๋ฐ ์ฒ๋ฆฌ๋์ง์๊ณ catch๋ก ์๋ฌ์ฒ๋ฆฌ๊ฐ ๋์ด๊ฐ๋๋ค.
์ด๊ฒ ์ด๋ป๊ฒ ๋ ์ผ์ธ์ง์??
Next.JS 14 ๋ฒ์ ์ด๊ธด ํฉ๋๋ค.
์ค๊ฐ์ OAuth ์ฒ๋ฆฌ ๊ตฌ๋ฌธ์ .env์ ์ฌ์ฉํ db ๋ช ์นญ์ ๋ช ์์ ์ผ๋ก ์ ์ธํ์ง์์์ test๋ผ๋ default db๊ฐ ์๊ฒจ์ ์ฒ๋ฆฌํ์ต๋๋ค.
-
์ด ๊ฒ์๊ธ์
Byeory์ ์ํด 1 ๋
, 7 ์ ์ ์ ์์ ๋์ต๋๋ค.
2024๋ 4์ 15์ผ 20:52 #120397
codingappleํค ๋ง์คํฐnotFound() ์คํ๋๋์ง ๋ฐ๋ก์์์ console.log๊ฐ์๊ฑฐ ์จ๋ด ์๋ค
-
์ด ๊ฒ์๊ธ์
-
๊ธ์ด์ด๊ธ
2 ๊ธ ๋ณด์ - 1 ์์ 2 ๊น์ง (์ด 2 ์ค์์)
- ๋ต๋ณ์ ๋ก๊ทธ์ธ ํ ๊ฐ๋ฅํฉ๋๋ค.
