본문 바로가기

Java Scripts/Vue.js

Vue : API calls with Axios

728x90

API Calls with Axios

Our app would make a request for the events, the server would respond with those events(as JSON), and we’d take those events and set them as our component’s data, which we then display in the view. 

우리 앱은 이벤트를 요청하고 서버는 해당 이벤트(JSON)로 응답하며 해당 이벤트를 component의 데이터로 설정한 다음 뷰에 표시합니다.

  • Create a mock database to house our events
  • Install a library (Axios) to make API Calls
  • Implement a getEvents() API call
  • Refactor our API code into a service layer

Our Mock Database

  1. Mock an API server we can call

API backends can be built using back-end frameworks like Laravel, Ruby on Rails, Express.js, or Django, to name a few.They can also be built using services like Firebase, Parse, Back4App, or Hoodie to name a few.

API 백엔드는 Laravel, Ruby on Rails, Express.js, Django 등의 백엔드 프레임워크를 사용하여 구축할 수 있습니다. 또한 Firebase, Parse, Back4App, Hood와 같은 서비스를 사용하여 구축할 수도 있습니다.

 

npm install -g json-server

json-server --watch db.json

  1. Install Axios
  2. Build the API call using Axios
  3. Use the event data in our component
  4. Reorganizing our Code

 

fake JSON server 를 만드는 절차

1. Create a JSON file on GitHub

    github.com/user/repo/main/db.json

db.json

{
 "events": [
 {
 "id": 123,
 "category": "animal welfare",
 "title": "Cat Adoption Day",
 "description": "Find your new feline friend at this
event.",
 "location": "Meow Town",
 "date": "January 28, 2022",
 "time": "12:00",
 "organizer": "Kat Laydee"
 },
 {
 "id": 456,
 "category": "food",
 "title": "Community Gardening",
 "description": "Join us as we tend to the community
edible plants.",
 "location": "Flora City",
 "date": "March 14, 2022",
 "time": "10:00",
 "organizer": "Fern Pollin"
 },
 {
 "id": 789,
 "category": "sustainability",
 "title": "Beach Cleanup",
 "description": "Help pick up trash along the shore.",
 "location": "Playa Del Carmen",
 "date": "July 22, 2022",
 "time": "11:00",
 "organizer": "Carey Wales"
 }
 ]
}

 

2. Get instantly a fake server

my-json-server.typicode.com/{GithubUserName}/{RepoName}/events

 

Axios for API Calls

Axios has a whole set of features, with the ability to:

  • Do GET, POST, PUT, and DELETE requests
  • Add authentication to each request
  • Set timeouts if requests take too long
  • Configure defaults for every request
  • Intercept requests to create middleware
  • Handle errors and cancel requests properly
  • Properly serialize and deserialize requests & responses

 

Implementing Axios to get events

delete out the hard-coded events data, import Axios, then add the created lifecycle hook.

하드 코딩된 이벤트 데이터를 삭제하고 Axios를 가져온 다음 created lifecycle hook.를 추가합니다.

src/views/EventList.vue

<script>
import EventCard from '@/components/EventCard.vue'
import axios from 'axios'
export default {
 	name: 'EventList',
 	components: {
 		EventCard
 	},
 	data() {
 		return {
 			events: null
       	}
 	},
 	created() {
		axios.get('https://my-json-server.typicode.com/CodePop/Real-World_Vue-3/events')
			.then(response => {
				this.events = response.data
			})
			.catch(error => {
			console.log(error)
			})
		}
}
</script>

Axios is a promise- based library and runs asynchronously, we need to be waiting for the promise returned from the get request to resolve before proceeding. That’s why we added the .then , which allows us to wait for the response and set our local events data equal to it.
Axios는 Promise 기반 라이브러리이며 비동기식으로 실행됩니다. 진행하기 전에 get 요청에서 반환된 Promise가 해결될 때까지 기다려야 합니다. 이것이 바로 우리가 응답을 기다리고 로컬 이벤트 데이터를 response와 동일하게 설정할 수 있도록 .then 을 추가한 이유입니다.

다른 방법으로 async / await 를 사용할 수 도 있다.

Exploring Async/Await Functions in JavaScript | DigitalOcean

 

Exploring Async/Await Functions in JavaScript | DigitalOcean

 

www.digitalocean.com

 

Reorganizing our code into a service layer

A cleaner and more scalable solution is to modularize our API code into a service layer.

더욱 깨끗하고 확장 가능한 솔루션은 API 코드를 서비스 계층으로 모듈화하는 것입니다.

 

src/services/EventService.js

import axios from 'axios'

const apiClient = axios.create({
  baseURL: 'https://my-json-server.typicode.com/Code-Pop/Real-World_Vue-3',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
})

export default {
  getEvents() {
    return apiClient.get('/events')
  },
  getEvent(id) {
    return apiClient.get('/events/' + id)
  }
}

we just need to make use of this new EventService within our EventList.vue component, deleting out the Axios import, importing the EventService, and running its getEvents() call.

EventList.vue component 내에서 이 새로운 EventService를 활용하고, Axios import를 삭제하고, EventService를 import하고, getEvents() 호출을 실행하면 됩니다.

 

src/views/EventList.vue

<template>
  <h1>Events for Good</h1>
  <div class="events">
    <EventCard v-for="event in events" :key="event.id" :event="event" />
  </div>
</template>

<script>
import EventCard from '@/components/EventCard.vue'
import EventService from '@/services/EventService.js'

export default {
  name: 'EventList',
  components: {
    EventCard
  },
  data() {
    return {
      events: null
    }
  },
  created() {
    EventService.getEvents()
      .then(response => {
        this.events = response.data
      })
      .catch(error => {
        console.log(error)
      })
  }
}
</script>

 

 

Resources

https://my-json-server.typicode.com/

 

My JSON Server - Fake online REST server for teams

my-json-server.typicode.com/user/repo/posts/1 { "id": 1, "title": "hello" }

my-json-server.typicode.com

 

https://github.com/Code-Pop/Real-World_Vue-3/tree/L5-end

 

GitHub - Code-Pop/Real-World_Vue-3: Example app for Vue Mastery's Real World Vue 3 course

Example app for Vue Mastery's Real World Vue 3 course - GitHub - Code-Pop/Real-World_Vue-3: Example app for Vue Mastery's Real World Vue 3 course

github.com

 

'Java Scripts > Vue.js' 카테고리의 다른 글

Vue : Error Handling and 404s  (0) 2022.01.16
Vue - Progress Bar : Axios Interceptors  (0) 2022.01.12
Vue : Global Component  (0) 2022.01.08
Vue : Single File Component  (0) 2022.01.08
Vue : Nested Routes  (0) 2022.01.08