axios: AJAX 데이터 받기 (Promise 기반) + 예제 (JSON 가져오기)
axios 홈페이지: https://github.com/axios/axios
사용법
axios는 Promise 기반의 AJAX 라이브러리입니다. 기본 형태는 다음과 같습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
axios.get('/user', {
params: {
ID: 'anyvalue'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
axios.get 뿐만 아니라 post, delete, put, patch 등 리퀘스트 종류에 따라 사용할 수 있습니다. then은 정상적으로 데이터를 받았을 경우 동작하며 catch는 에러 캐치, finally는 동작 여부와 무관하게 무조건 실행되는 부분입니다. 받은 데이터(JSON 등) 만 추출하고 싶은 경우 response.data 로 가져옵니다.
예제 (Vue.js 포함)
퀴즈 카드를 만드는 예제입니다. 데이터 출처는 [링크]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container">
<div id="main-app" >
<template v-for="(item, index) in message">
<quiz v-for="(cont, key) in item" v-bind:quiz-inner="cont" v-bind:quiz-key="index" ></quiz>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<script>
(...)
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 스트링을 대문자화
Vue.filter('capitalize', function(value) {
if (!value) return ''
value = value.toString()
return value.toUpperCase()
})
// 퀴즈 컴포넌트 선언
Vue.component('quiz', {
template: `<div class="card border-primary mb-3" style="max-width: 20rem; " >
<div class="card-header"></div>
<div class="card-body">
<h4 class="card-title"></h4>
<li class="card-text" v-for="option in quizInner.options">{{option == quizInner.answer ? option + ' (answer)' : option}}</li>
</div>
</div>`,
props: ['quizInner', 'quizKey']
})
var mainApp = new Vue({
el: '#main-app',
data: {
message: 'You loaded this page on ' + new Date().toLocaleString()
},
created: function() {
const self = this
/** == AXIOS get으로 가져오기 == **/
axios.get('https://support.oneskyapp.com/hc/en-us/article_attachments/202761727/example_2.json')
.then(response => {
// handle success
console.log(response.data, this);
this.message = response.data.quiz
})
/** ========================= **/
}
})
Vue.js에서 filter로 선언한 부분은 `` 으로 사용합니다. created 안의 부분은 컴포넌트 라이프사이클에서 created 되었을 때 실행합니다.
This post is licensed under
CC BY 4.0
by the author.
