728x90
프로젝트 중심
-----------------------------------------------------------------------------------------------------
게시판 DB 연동 중 (상세 페이지 추가 예정)
게시판 관련 코드를 짜면서 MySQL 데이터 베이스와 연동을 시키는 과정을 거쳤다.
Board 컴포넌트
import React, { Component } from "react";
import "../css/Board.css";
import BoardList from "./Board/BoardList.js"
import Pagination from "./Pagination.js";
import axios from "axios";
import NewBoard from "./Board/NewBoard.js";
class Board extends Component {
constructor(props) {
super(props);
this.state = {
boardList: [],
boardPerPage: 10,
currentPage: 1,
showNewBoard: false,
};
}
componentDidMount() {
this.fetchBoardList();
}
fetchBoardList = () => {
const { boardPerPage, currentPage } = this.state;
const offset = (currentPage - 1) * boardPerPage;
const apiUrl = `/board?limit=${boardPerPage}&offset=${offset}`;
axios
.get(apiUrl)
.then((response) => {
this.setState({ boardList: response.data });
})
.catch((error) => {
console.error("Error fetching board list:", error);
});
};
handleToggleNewBoard = () => {
this.setState((prevState) => ({
showNewBoard: !prevState.showNewBoard,
}));
};
formatDateString(dateString) {
const date = new Date(dateString);
const options = { year: "numeric", month: "2-digit", day: "2-digit" };
return date.toLocaleDateString("ko-KR", options);
}
handlePageChange = (pageNumber) => {
this.setState({ currentPage: pageNumber }, () => {
this.fetchBoardList();
});
};
render() {
const { boardList, boardPerPage, currentPage, showNewBoard } = this.state;
if (boardList.length === 0) {
return (
<div id="board">
<p>게시글이 없습니다.</p>
</div>
);
}
const totalBoards = boardList.length;
const lastPage = Math.ceil(totalBoards / boardPerPage);
if (currentPage > lastPage) {
this.setState({ currentPage: lastPage }, () => {
this.fetchBoardList();
});
}
if (showNewBoard) {
return <NewBoard fetchBoardList={this.fetchBoardList} />;
}
const indexOfLastBoard = currentPage * boardPerPage;
const indexOfFirstBoard = indexOfLastBoard - boardPerPage;
const currentBoardList = boardList.slice(
indexOfFirstBoard,
indexOfLastBoard
);
const formattedBoardList = currentBoardList.map((board) => ({
...board,
writeDate: this.formatDateString(board.writeDate),
}));
return (
<div id="board">
<BoardList boardList={formattedBoardList} />
<Pagination
total={totalBoards}
itemsPerPage={boardPerPage}
currentPage={currentPage}
onPageChange={this.handlePageChange} // setCurrentPage 대신 onPageChange를 전달
/>
<div id="new-write">
<button onClick={this.handleToggleNewBoard}>글쓰기</button>
</div>
</div>
);
}
}
export default Board;
Server
app.get("/board", (req, res) => {
console.log("/board");
db.query("select * from board order by no DESC", (err, data) => {
if (!err) {
//console.log(data)
res.send(data);
} else {
console.log(err);
}
});
});
app.get("/board/:no", (req, res) => {
console.log("/board/:no");
const no = req.params.no;
db.query(`select * from board where no=${no}`, (err, data) => {
if (!err) {
res.send(data);
} else {
console.log(err);
}
});
});
app.post("/board", (req, res) => {
console.log("/board(POST)");
console.log(req.body);
const { title, contents, writer, writeDate } = req.body;
db.query(
`insert into board(title,contents,writer,writeDate)
values('${title}','${contents}','${writer}','${writeDate}')`,
(err, data) => {
if (!err) {
res.send(data);
} else {
console.log(err);
}
}
);
});
app.put("/board/:no", (req, res) => {
console.log("/board/:no(PUT)");
const no = req.params.no;
console.log(no);
console.log(req.body);
const { title, contents, writer, writeDate } = req.body;
db.query(
`update board set title='${title}',contents='${contents}',writer='${writer}', writeDate='${writeDate}' where no=${no}`,
(err, data) => {
if (!err) {
res.send(data);
} else {
console.log(err);
}
}
);
});
app.delete("/board/:no", (req, res) => {
console.log("/board/:no(DELETE)");
const no = req.params.no;
db.query(`delete from board where no=${no}`, (err, data) => {
if (!err) {
res.send(data);
} else {
console.log(err);
}
});
});
728x90