JSON Server란?
- JSON Server는 간단한 REST API 서버를 실행할 수 있는 툴입니다.
- 데이터베이스를 따로 구축하지 않고, JSON 파일을 이용해 서버 역할을 수행할 수 있습니다.
- 리액트 앱에서 서버 요청 테스트를 할 때 매우 유용합니다.
1. 설치
npm install -g json-server
2. 데이터 파일 작성: db.json이라는 파일을 만듭니다
{
"posts": [
{ "id": 1, "title": "Hello World", "content": "Welcome to JSON Server" },
{ "id": 2, "title": "Learning React", "content": "React is awesome!" }
]
}
3. 서버 실행: 아래 명령어로 JSON Server를 실행합니다.
json-server --watch db.json
React에서 JSON Server 사용 예제
1. GET 요청으로 데이터 읽기
fetch("http://localhost:3000/posts")
.then(response => response.json()) // JSON 형식의 데이터를 JavaScript 객체로 변환
.then(data => console.log(data)) // 데이터 출력
.catch(error => console.error("에러 발생:", error));
2. POST 요청으로 데이터 추가
fetch("http://localhost:3000/posts", {
method: "POST",
headers: {
"Content-Type": "application/json", // 보낼 데이터가 JSON 형식임을 명시
},
body: JSON.stringify({ title: "New Post", content: "This is a new post" }),
})
.then(response => response.json())
.then(data => console.log("추가된 데이터:", data))
.catch(error => console.error("에러 발생:", error));
'sparta > REACT' 카테고리의 다른 글
[REACT] 스탠다스 심화주차 복습 (0) | 2024.11.25 |
---|---|
[REACT] 심화주차 - Axios (0) | 2024.11.24 |
[REACT] 심화주차 - 비동기, 동기 (1) | 2024.11.24 |
[REACT] 강의 모르는 용어 (0) | 2024.11.23 |
[REACT]JSON (0) | 2024.11.19 |