서버 기능 만들기
pages/api
폴더 아래에 만든 폴더와 파일은 자동으로 서버 기능의 URL이 된다.
글 작성 기능
// app/write/pages.jsx
export default function write() {
return (
<div className="p-20">
<h4>글 작성 페이지</h4>
<form action="/api/post/new" method="POST">
제목: <input type="text" name="title" />
내용: <input type="text" name="content" />
<button type="submit">입력</button>
</form>
</div>
);
}
form
의 action
에 적은 경로의 서버로 데이터가 전송된다.
// pages/api/post/new.js
import { connectDB } from '@/util/database';
export default async function handler(request, response) {
if (request.method === 'POST') {
if (request.body.title === '') {
return response.status(500).json('제목도 써라');
}
try {
const client = await connectDB;
const db = client.db('forum');
await db.collection('post').insertOne(request.body);
return response.status(200).redirect(302, '/list');
} catch (err) {
return response.status(500).json('db저장 에러');
}
}
}
request.body
로 전송받은 데이터가 담겨서 온다.
받은 데이터를 insertOne
을 통해 db에 저장한다.
글 수정 기능
// app/edit/[id]/pages.jsx
import { connectDB } from '@/util/database';
import { ObjectId } from 'mongodb';
import Link from 'next/link';
export default async function Edit(props) {
const client = await connectDB;
const db = client.db('forum');
let result = await db.collection('post').findOne({ _id: new ObjectId(props.params.id) });
return (
<div className="p-20">
<h4>글 수정 페이지</h4>
<form action="/api/post/edit" method="POST">
제목: <input type="text" name="title" defaultValue={result.title} />
내용: <input type="text" name="content" defaultValue={result.content} />
<input
style={{ display: 'none' }}
name="_id"
defaultValue={result._id.toString()}
/>
<button type="submit">입력</button>
<Link href="/list">목록</Link>
</form>
</div>
);
}
Point는 두 가지.
[id]
폴더를 만들어 [dynamic route]
설정.
findOne
을 통해 클릭한 게시글의 id 획득.
defaultValue
속성 이용.
// pages/api/post/edit.js
import { connectDB } from '@/util/database';
import { ObjectId } from 'mongodb';
export default async function handler(request, response) {
if (request.method === 'POST') {
console.log(request.body);
let newObj = { title: request.body.title, content: request.body.content };
console.log('newObj', newObj);
try {
const client = await connectDB;
const db = client.db('forum');
let result = await db
.collection('post')
.updateOne({ _id: new ObjectId(request.body._id) }, { $set: newObj });
console.log('result', result);
response.status(200).redirect(302, '/list');
} catch (err) {
console.log('catch 에러');
return response.status(500).json('catch 에러');
}
} else console.log('try도 못드감');
}
updateOne({수정할 게시물 정보}, { $set : {수정할 내용} } );
보통 수정할 게시물 정보
는 id
를 이용.
request.body
에는 id
가 없다.
여기에선 사용자에게 받았다.
애초에 page.jsx
input에 defaultValue
에 해당 id를 설정해두고, display:none
한다.