JSON Server와 Axios를 사용한 간단한 RESTful API 구현
JSON Server와 Axios를 사용하면 몇 분 만에 완벽한 API를 구축하고 데이터를 조작할 수 있습니다.
JSON Server로 API를 설정하고 Axios로 데이터를 가져오고 조작하는 방법을 단계별로 설명해보겠습니다.
1. JSON Server 설치 및 설정
JSON Server는 JSON 파일을 기반으로 가상의 REST API를 생성해주는 도구입니다. 이를 통해 백엔드 없이 프론트엔드 개발을 빠르게 시작할 수 있습니다.
Step 1: JSON Server 설치
먼저, JSON Server를 설치합니다.
yarn add json-server
Step 2: 데이터 파일 생성
JSON Server가 읽을 수 있는 db.json 파일을 생성합니다. 이 파일에 초기 데이터를 넣어줍니다.
{
"posts": [
{ "id": 1, "title": "Hello World", "author": "John Doe" },
{ "id": 2, "title": "JSON Server is Awesome", "author": "Jane Smith" }
],
"comments": [
{ "id": 1, "postId": 1, "body": "Great post!", "author": "Alice" },
{ "id": 2, "postId": 2, "body": "Very informative.", "author": "Bob" }
]
}
Step 3: JSON Server 실행
이제 JSON Server를 실행하여 API를 시작합니다.
json-server --watch db.json
이 명령을 실행하면 http://localhost:3000에서 API가 실행됩니다. 이제 브라우저에서 http://localhost:3000/posts와 같은 엔드포인트로 데이터를 확인할 수 있습니다.
2. Axios를 사용한 데이터 가져오기 및 조작
이제 Axios를 사용하여 JSON Server로부터 데이터를 가져오고 조작하는 방법을 알아보겠습니다. Axios는 브라우저와 Node.js에서 사용할 수 있는 인기 있는 HTTP 클라이언트입니다.
Step 1: Axios 설치
프로젝트에 Axios를 설치합니다.
yarn add axios
Step 2: 데이터 가져오기
다음은 Axios를 사용하여 JSON Server로부터 데이터를 가져오는 예제입니다.
import axios from 'axios';
// GET 요청: 모든 포스트 가져오기
axios.get('http://localhost:3000/posts')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching posts:', error);
});
Step 3: 데이터 추가
포스트를 추가하는 예제입니다.
// POST 요청: 새로운 포스트 추가
axios.post('http://localhost:3000/posts', {
title: 'New Post',
author: 'New Author'
})
.then(response => {
console.log('Post added:', response.data);
})
.catch(error => {
console.error('Error adding post:', error);
});
Step 4: 데이터 업데이트
기존 포스트를 업데이트하는 예제입니다.
// PUT 요청: 포스트 업데이트
axios.put('http://localhost:3000/posts/1', {
title: 'Updated Title',
author: 'Updated Author'
})
.then(response => {
console.log('Post updated:', response.data);
})
.catch(error => {
console.error('Error updating post:', error);
});
Step 5: 데이터 삭제
포스트를 삭제하는 예제입니다.
// DELETE 요청: 포스트 삭제
axios.delete('http://localhost:3000/posts/1')
.then(response => {
console.log('Post deleted:', response.data);
})
.catch(error => {
console.error('Error deleting post:', error);
});
마무리
이렇게 해서 JSON Server와 Axios를 사용하여 간단한 RESTful API를 구현하고 데이터를 조작하는 방법을 알아보았습니다. JSON Server는 빠르고 간단하게 API를 설정하는 데 유용하며, Axios는 이러한 API와 상호작용할 때 매우 편리한 도구입니다. 이 두 가지를 사용하면 프론트엔드 개발을 더 효율적으로 진행할 수 있습니다.