728x90
글작성기능을 해봤다
그래서 몽고디비에 데이터가 삽입되는 기능을 해봤다.
일단 get과 post기능은 form을 이용하면 쉽게 하기 좋단다
write/page.js
export default function Write() {
return (
<div className="p-20">
<h4>글작성페이지</h4>
{/* get이랑 post하는 방법을 배워보자 */}
<form action="/api/post/new" method="POST">
<input name="title" placeholder="글제목부분" />
<input name="content" placeholder="글내용부분" />
<button type="submit">버튼</button>
</form>
</div>
);
}
pages/api/post/new.js
import { connectDB } from "@/util/database";
export default async function handler(요청, 응답) {
if (요청.method == "POST") {
const client = await connectDB;
const db = client.db("market");
let result = await db.collection("post").insertOne(요청.body);
return 응답.status(200).json("저장완료");
}
}
이렇게 insertOne을 이용하면 mongoDb에 데이터를 삽입하는 기능을 할수있다.
응답과 동시에 페이지 이동하는 기능으로 redirect로 하려면 이렇게 하면된다.
import { connectDB } from "@/util/database";
export default async function handler(요청, 응답) {
if (요청.method == "POST") {
const client = await connectDB;
const db = client.db("market");
let result = await db.collection("post").insertOne(요청.body);
return 응답.redirect(302, "/list");
}
}
728x90
'교육후 개인공부 > React' 카테고리의 다른 글
[Next.js] dynamic route와 id맞추기(상세페이지설정) (0) | 2024.02.20 |
---|---|
mongoDb 연결하기 (0) | 2024.02.20 |
[Next.js] Oauth google 구현하기 (0) | 2023.12.09 |
[Next.js] 게시물수정하기 (0) | 2023.12.07 |
[React] todolist 구현완성본 (1) | 2023.12.06 |