컴퓨터 프로그래밍/Next.js

[Next.js] API 요청 구현하기 ( 글작성, 글수정 )

한33 2025. 4. 22. 21:59

💡 글작성 페이지 만들기

export default function Write() {
    return (
        <div className="p-20">
            <h4>글작성</h4>
            <form action="/api/post/new" method="POST">
                <input name="title" placeholder="글제목"/>
                <input name="content" placeholder="글내용"/>
                <button type="submit">버튼</button>
            </form>
        </div>
    );
}

 

우선 /write 경로로 페이지를 만들어줬다.

form 태그를 사용해 위처럼 api uri 와 method 를 설정해준 후에 input 태그의 name 을 설정해주고 button 에 submit type 을 설정해주면 버튼 클릭 시 해당 데이터들이 서버로 전달된다.

💡 글작성 서버 만들기

최상단 경로에 pages 라는 폴더명과 함께 위처럼 파일을 만들면 /api/post/new 이렇게 api 요청을 보낼 수 있다.

import {connectDB} from "@/util/database";

export default async function handler(req, res) {
    if (req.method === 'POST') {
        if (req.body.title === '') {
            return res.status(500).json('제목 안 씀')
        }
        try {
            const db = (await connectDB).db("forum")
            let result = await db.collection('post').insertOne(req.body)
            return res.status(200).redirect('/list')
        } catch (error) {
            return res.status(500).json('DB 에러')
        }
    }
}

 

그런 다음 if 문을 사용해서 HTTP method 를 정해준다. 따로 정하지 않으면 모든 method 가 같은 로직을 타게 된다.

필자는 title 이 비어있을 시에 에러를 응답하고,

try-catch 문으로 forum database 의 post collection 에 해당 데이터를 저장시킨 후 /list 로 redirect 시켰다.

혹시 DB 연결에 문제가 생길 수 있기 때문에 예외처리를 해주었다.

💡 글수정 페이지 만들기

<input style={{display: 'none'}} name="_id" defaultValue={result._id.toString()}/>

 

글 수정 페이지는 글 작성 페이지와 동일한데 추가로 id 값을 함께 body 로 전달시키기 위해 input 태그를 추가하고 보이지 않도록 style 을 추가해줬다.

서버측에서는 id 를 알 방법이 없기 때문에 이처럼 직접 전해주었다.

export default async function handler(req, res) {
    if (req.method === 'POST') {
        if (req.body.title === '') {
            return res.status(500).json('제목 안 씀')
        }
        let data = {
            title : req.body.title,
            content: req.body.content
        }
        try {
            const db = (await connectDB).db("forum")
            let result = await db.collection('post').updateOne({_id : new ObjectId(req.body._id)}, {$set : data})
            return res.status(200).redirect('/list')
        } catch (error) {
            return res.status(500).json('DB 에러')
        }
    }
}

 

이후 위처럼 updateOne 메서드를 통해서 변경하고자 하는 id 값을 지정해주고, $set 을 통해 기존 데이터의 key 값들과 value 를 지정해서 덮어쓰기 해주었다.

$inc 를 사용하면 숫자만 증가하든지 할 수 있다.