axios를 이용한 서버통신

서버와 통신하기 위한 라이브러리는 fetch, superagent, axios 등이 있으며 Vue.js 플러그인으로 개발된 vue-resource라는것도 존재하나 Vue.js 창시자인 에반 유는 axios를 사용할 것을 권장하고 있다고 한다.


서비스 API

S네트워크 사용에 제약이 따를 경우 로컬에서 실행할 수 있는 API코드를 다운로드하여 실행하는 연락처 서비스 API이다.


다운로드 >> https://github.com/STEPANOWON/CONTACTSVC



[저수준 API]

axios(config)

axios(url, config]


[각 메서드별 별칭]

axios.get(url[, config])

axios.delete(url[, config])

axios.psot(url[, data[, config])

axios.put(url[, data[, config])

axios.head(url[, config])

axios.options(url[, config])



axios 사용법


yarn add axios 


Or


npm install --save axios






axios 프로젝트 생성



1) vue cli로 프로젝트 생성

vue create contactsapp

2) axios 추가 

yarn add axios OR npm install --save -axios

3) http proxy 설정

Vue CLI가 생성하는 프로젝트 템플릿 코드에서는 약간의 설정 파일만 작성하면 웹팩 개발서버를 이용해 프로시 서버 기능을 사용할 수 있다. 프로젝트 최상위 디렉토리에 vue.config.js파일을 생성하고 아래의 코드를 작성한다.

module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localshot:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}


이렇게 하면 개발용 서버에 /api/contacts를 요청하게되면 http://localshot:3000/contacts로 요청일 전달 도니다.  만약 위의 서비스 API 서버를 로컬에서 실행하지 않는다면 위의 target 값을 http://sample.bmaster.kro.kr 으로 지정하면 된다.




<template>
<div id="app">
<div class="container">
<div class="form-group">
<button @click="fetchContacts">1페이지 연락처 조회</button>
</div>
<div class="form-group">
<input type="text" v-model="name"
placeholder="이름을 입력합니다"/>
<input type="text" v-model="tel"
placeholder="전화번호를 입력합니다"/>
<input type="text" v-model="address"
placeholder="주소 입력합니다"/>
<button @click="addContact">연락처 1건 추가</button>
</div>
<div class="form-group">
<input type="text" v-model="no"/>
<button @click="fetchContactOne">연락처 1건 조회</button>
</div>
<div class="form-group">
<input type="text" v-model="no"/>
<input type="text" v-model="name"
placeholder="이름을 입력합니다"/>
<input type="text" v-model="tel"
placeholder="전화번호를 입력합니다"/>
<input type="text" v-model="address"
placeholder="주소 입력합니다"/>
<button @click="updateContact">수정</button>
</div>
<div class="form-group">
<input type="text" v-model="no"/>
<input type="file" ref="photofile" name="photo"/>
<button @click="changePhoto">파일 변경</button>
</div>
</div>
<span>JSON 출력</span>
<div id="result" class="container">
<xmp> {{ result }} </xmp>
</div>
</div>
</template>

<script>
import axios from 'axios';

export default {
name : "app",
data() {
return {
no: 0,
name: '',
tel: '',
address: '',
result: null
}
},
methods : {
fetchContacts : function() {

},

addContact : function() {

},

fetchContactOne : function() {

},

updateContact : function() {

},

deleteContact : function() {

},

changePhoto : function() {

}
}
}
</script>

<style>
@import url("http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.css");
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osz-font-smoothing: grayscale;
text-align: center;
color : #2c3e50;
margin-top : 60px;
}

.container {
border: solid 1px gray;
padding: 10px;
margin-bottom: 10px;
text-align: left;
}

#result {
text-align: left;
padding: 20px;
border: solid 1px black;
}

.form-group {
border: dashed 1px gray;
padding: 5px 5px 5px 20px;
}
</style>

[src/AppAxiosTest.vue]




import Vue from 'vue'
//import App from './App.vue'
import App from './AppAxiosTest.vue'

Vue.config.productionTip = false

new Vue({
render: h => h(App),
}).$mount('#app')

[src/main.js]




axios 요청 방법

axios 저수준 API를 이용하는 예제이다. 아래의 코드를 fetchContact메서드에 작성한다.


fetchContacts : function() {
axios({
method: 'GET',
url : '/api/contacts',
params : {
page : 1,
pagesize : 5
}
}).then((response) => {
console.log(response);
this.result = response.data;
}).catch((ex)=> {
console.log("ERR!!!!! : ", ex)
})
},

[ 저수준 axios 메소드 작성법 ]



axios 저수준 메서드의 특징은 모든 전달값을 config 객체로 전달한다는 특징이 있다. Promise 객체는 요청이 성공적이라면 then이 호출되며 요청이 실패하면 catch가 호출된다. 저수준 메서드가 아닌 별칭 메서드 get을 이용하여 fetchContactOne을 작성하겠다.



fetchContactOne : function() {
axios.get('/api/contacts/' + this.no)
.then((response) => {
console.warn(response);
this.result = response.data
})
},

[GET]



POST 메서드에서는 주로 axios.post(url, data, config) 형태를 주로 사용한다. 다음은 addContact 에 POST를 이용해 작성해본 코드이다.



addContact : function() {
axios.post('/api/contacts',
{ name:this.name, tel:this.tel, address:this.address }
).then(response => {
console.warn(response)
this.result = response.data
this.no = response.data.no
}).catch((ex) => {
console.warn("ERROR!!!!! : ",ex)
})
},

[POST]



updateContact : function() {
axios.put('/api/contacts/' + this.no,
{ name:this.name, tel:this.tel, address:this.address }
).then(response => {
console.warn(response)
this.name = '';
this.tel = '';
this.address = '';
this.result = response.data
}).catch((ex) => {
console.warn("ERROR!!!!! : ",ex)
})
},

[PUT]



deleteContact : function() {
axios.delete('/api/contacts/' + this.no)
.then(response => {
console.warn(response)
this.result = response.data
}).catch((ex) => {
console.warn("ERROR!!!!! : ",ex)
})
},

[DELETE]



파일 업로드 기능도 axios로 구현하기 위해서는 위에 작성한 <input tpye="file" ../> 필드를 직접 참조해야한다. 해당 태그에 보면 ref="photofile" 이라고 ref 옵션을 사용한걸 볼 수 있다. 


changePhoto : function() {
var data = new FormData();
var file = this.$ref.photofile.files[0]
data.append('photo', file)

axios.post('/api/contacts' + this.no + '/photo', data)
.then(response => {
console.warn(response)
this.result = response.data
this.no = response.data.no
}).catch((ex) => {
console.warn("ERROR!!!!! : ", ex)
})
}

[File 전송]



FormData 객체를 생성하고 this.$ref.photofile과 같이 ref 옵션을 이용해 파일 필드를 직접 참조할 수 있다. 이 필드의 값을 FormData 객체에 추가한뒤 서버로 요청하게 된다.




Vue Instance 내부에서 axios 이용하기

Vue 인스턴스 내부에서 axios를 이용하기 위해 Vue.prototype에 axios를 추가하면 간단하게 사용 할 수있다. main.js에 아래의 내용을 추가한다.


import Vue from 'vue'
//import App from './App.vue'
import App from './AppAxiosTest.vue'
import axios from '.axios'

Vue.prototype.$axios = axios;
Vue.config.productionTip = false

new Vue({
render: h => h(App),
}).$mount('#app')

[src/main.js]


이렇게 작상하면 Vue 인스턴스 내부에서는 axios를 따로 improt하지 않아도 this.$axios를 이용해서 사용할 수 있다. AppAxiosTest.vue 파일의 fetchContactone 메서드는 아래와 같이 변경할 수 있다.


fetchContactOne : function() {
this.$axios.get('/api/contacts/' + this.no)
.then((response) => {
this.result = response.data
})
},




axios 사용 시 주의 사항

axios를 사용하면서 then() 처리를 할 때는 ECMAScript6의 화살표 함수를 사용할 것을 권장한다. 데이터를 수신한 후에 Vue 인스턴스 내부의 데이터를 변경해야 하는 경우가 있는데 데이터 옵션을 액세스하기 위해서는 this 객체가 Vue인스턴스를 참조할 수 있어야 한다. then() 내부에서 화살표 함수를 하용하지 않으면 this가 vue 인스턴스를 참조하지 않기 때문에 밖에서 별도의 변수에 this를 할당한 후에 클로저 방식으로 접근해야 하는 불편함이 발생한다. 

















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

[Vue.js] Vuex를 이용한 상태 관리 (store, mutation, getter)  (0) 2018.12.23
[Vue.js] Vue CLI(GUI)  (0) 2018.12.18
[Vue.js] Component  (0) 2018.12.18
[Vue.js] Event 처리  (0) 2018.12.17
[Vue.js] Vue instance (뷰 인스턴스)  (0) 2018.12.16

+ Recent posts