vue3 Json DB 설정
업데이트:
카테고리: vue3
/json 서버 패키지 설치
- 백엔드 서버가 없다면 계속 새로고침 할 때 마다 데이터가 없어짐
 - 가짜 DB로 새로고침마다 날라가는 것을 방지 (개발 중에만 사용)
 
npm install -g json-server패키지 설치- 파일 최상단에 
db.json파일 생성 후 - 객체 형태로 데이터 베이스 테이블 생성하기
 
{
// 데이터 베이스 테이블
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
json-server --watch db.json로 db.json 구동
db에 데이터 저장하기 (post)
npm i axios : db와 응답을 주고받기 위해서는 axios가 필요
post 요청 ( 프론트 » 백엔드)
const addTodo = (todo) => {
      // 데이터베이스에 저장
      axios.post('http://localhost:3000/todos', {
        subject: todo.subject,
        completed: todo.completed
				}
      todos.value.push(todo)
    }
axios.post(’보낼 url’, 데이터) 작성하여 데이터를 보낸다.
이때 요청은 promise 형식으로, 비동기적으로 발생하기 때문에 위와같이 코드를 작성하면 post 요청을 다 보내기도 전에 todos 리스트에 데이터가 들어가게 된다.
요청이 정상적으로 잘 들어가고 나서 데이터가 보여져야 하므로 아래와 같이 코드를 작성해한다.
const addTodo = (todo) => {
      // 데이터베이스에 저장
      axios.post('http://localhost:3000/todos', {
        subject: todo.subject,
        completed: todo.completed,
			// 정상적으로 실행
      }).then(res => {
        console.log(res)
        todos.value.push(todo)
			// 오류 발생
      }).catch(err => {
        console.log(err)
      })
    }
then(res => {}) 은 axios 요청이 정상적으로 처리 된 후 실행할 코드를 작성하는 것이다.
catch(err => {}) 는 axios 요청이 실패했을 경우 에러를 처리하는 코드를 작성하는 것이다.
db 에서 데이터 가져오기 (get)
axios.get 요청으로 데이터를 받아와 초기 데이터 구성
get 요청 (백엔드 » 프론트)
const getTodos = async () => {
      try {
        const res = await axios.get('http://localhost:3000/todos')
        todos.value = res.data
      } catch (err) {
        error.value = 'Something went wrong'
      } 
    }
    getTodos()
db 에서 get 요청으로 데이터를 받아와 초기값으로 설정
db에서 데이터 삭제 (delete)
화면에서 뿐만 아니라 db에서도 삭제하기 위해 axios.delete 요청
삭제에는 아이디 값이 필요하므로 해당 아이디 값을 특정하여 보낸다.
const deleteTodo = async (index) => {
      // 해당 todos의 아이디를 찾아냄
      const id = todos.value[index].id
      try {
        const res = await axios.delete('http://localhost:3000/todos/' + id)
        console.log(res)
        todos.value.splice(index, 1)
      } catch (err) {
        console.log(err)
      }
    }
db에 실시간 데이터 변경 반영하기 (PUT, PATCH)
PUT : 데이터 전체 변경
PATCH : 데이터 부분 변경
const toggleTodo = async (index) => {
      error.value = ""
      const id = todos.value[index].id
      try {
        await axios.patch('http://localhost:3000/todos/' + id, {
          completed: !todos.value[index].completed
        })
        // todos.value[index].completed = !todos.value[index].completed
      } catch (err) {
        console.log(err)
        error.value = 'Something went wrong'
      }
    }
post와 같이 url과 데이터를 보낸다.
비동기적 실행
동기적 : 순차적으로 발생
비동기적 : 완성되는 순서대로 실행
위와 같이 axios 요청을 보내고 then, catch 형식으로도 비동기적 실행이 가능하나 코드가 복잡해지면 코드가 깊이 빠져들어가 가독성이 안좋게 된다.
그래서 사용하는 방법이 async, await
const addTodo = async (todo) => {
      // 데이터베이스에 저장
      error.value = ""
      try{
        const res = await axios.post('http://localhost:3000/todos', {
          subject: todo.subject,
          completed: todo.completed,
        })
        todos.value.push(res.data)
      } catch (err) {
        error.value = 'Something went wrong'
      }
}
실행할 함수 앞에 async 를 작성하고 비동기적 실행이 필요한 코드 앞에 await 를 작성하면 된다.
만약 에러를 잡아야 한다면 try, catch 구문으로 작성이 가능하다