설치 및 실행
npm install -g json-server
db.json 파일 만들기
{
"posts": [
{ "id": 1, "title": "서버 글1", "content": "내용입니다." },
{ "id": 2, "title": "서버 글2", "content": "내용입니다." },
{ "id": 3, "title": "서버 글3", "content": "내용입니다." },
{ "id": 4, "title": "서버 글4", "content": "내용입니다." },
{ "id": 5, "title": "서버 글5", "content": "내용입니다." },
{ "id": 6, "title": "서버 글6", "content": "내용입니다." },
{ "id": 7, "title": "서버 글7", "content": "내용입니다." },
{ "id": 8, "title": "서버 글8", "content": "내용입니다." },
{ "id": 9, "title": "서버 글9", "content": "내용입니다." },
{ "id": 10, "title": "서버 글10", "content": "내용입니다." }
]
}
-> 프로젝트 루트에 생성
json-server 실행하기
json-server --watch db.json --port 3001
http://localhost:3001/posts
GET /posts, POST /posts, PUT /posts/1, DELETE /posts/1 등이 REST API로 제공됩니다.
React에서 호출하기
PostContext.jsx 수정하기
// useEffect(() => {
// localStorage.setItem('posts', JSON.stringify(posts));
// }, [posts]);
useEffect(() => {
fetch('http://localhost:3001/posts')
.then(res => res.json())
.then(data => setPosts(data));
}, []);
-> 이 방식은 학습이나 실제 API 연동 전 시뮬레이션 용도로 적합.
반응형
'프로그래밍 > React' 카테고리의 다른 글
| React로 블로그 만들기 - 글 삭제 기능 추가하기 (9) (0) | 2025.07.06 |
|---|---|
| React로 블로그 만들기 - 간단한 UI 구성 및 레이아웃 구성하기 (8) (0) | 2025.07.06 |
| React로 블로그 만들기 - 데이터 저장 유지 – localStorage (6) (0) | 2025.07.06 |
| React로 블로그 만들기 - 폼 컴포넌트 분리 및 재사용 (5) (0) | 2025.07.06 |
| React로 블로그 만들기 - 글 상세 보기 + 수정 기능 + 댓글 기능 구현 (4) (0) | 2025.07.06 |