Axios는 Promise
기반의 자바스크립트 비동기 처리 방식을 사용하고 있기 때문에 아래와 같이 서버를 호출한 후에 반횐되는 콜백함수를 통해서 결과를 처리하는 방식으로 운영된다.
axios.get('/api/data')
.then(res => {
console.log(res.data);
});
설치는 프로젝트에 axios 패키지를 설정하면 된다.
$ npm install -s axios
# 또는
$ yarn add axios
요즘 그럴일은 없겠지만 단순한 웹구성을 사용하고 있다면 직접 웹페이지에 스크립트를 지정해서 사용할 수도 있다.
...
<head>
...
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
...
</head>
...
axios는 REST 메서드 이름을 별칭으로 사용하기 때문에 사용하기 쉽다.
axios.get(url[, config])
axios.post(url[, data[, config]])
axios.patch(url[, data[, config]])
axios.delete(url[, config])
서버에서 데이터를 가져오는 용도로 가장 많이 사용되는 명령이다.
// 단순 데이터 조회
axios.get('/aip/data/1')
.then(res => {
console.log(`status: ${res.status}`); // 응답 Status code
console.log(`headers: ${res.headers}`); // 응답 Headers
console.log(`data: ${res.data}`); // 응답 Data
});
// 요청 데이터 포함
axios.get('/api/data', {
params: { title: 'axios test' }, // 요청으로 전달할 데이터
headers: { 'X-Api-Key': 'my-api-key' }, // Header로 전달할 데이터
timeout: 1000 // Timeout 1초. 지나면 오류 처리
}).then(res => {
console.log(res.data)
});
서버로 데이터를 등록(입력)할 떄 사용되는 명령이다.
axios.post('/aip/data', {
title: 'axios test'
}).then(res => {
console.log(res.data)
});
서버의 특정한 데이터를 수정할 때 사용되는 명령이다.
axios.post('/aip/data/3', {
title: 'axios test'
}).then(res => {
console.log(res.data)
});
서버의 특정한 데이터를 삭제할 때 사용되는 명령이다.
axios.post('/aip/data/3')
.then(res => {
console.log(res.data)
});
HTML 구문을 Upload로 사용하기 위해서 Form 구성을 아래와 같이 한다.
<form method="post" enctype="multipart/form-data" action="/content/data">
<input type="file" name="image" ref="photo">
<input type="submit">
</form>
FormData()
객체를 생성하고 this.$ref.photo
와 같이 ref 옵션을 이용해서 필드를 직접 참조를 해서 이미지 파일을 가져오고 업로드할 수 있다. 처리하는 스크립트는 아래와 같다.
// FormData 생성 및 이미지 파일 가져오기
var data = new FormData();
var file = this.$ref.photo.files[0];
data.append('photo', file);
// axios로 파일 업로드 처리
axios.post('/api/data' + this.no + 'photo', data)
.then((res) => {
this.result = res.data;
})
.catch((ex) => {
console.log('파일 업로드 실패:', ex);
});
axios-module 은 Nuxt.js에서 공식 지원하는 모듈로 Nuxt 환경에서 Axios를 쉽고 안전하게 사용할 수 있도록 지원하는 것이다. 이 모듈에 대한 것은 API 사용법을 참고하도록 한다.
$ yarn add @nuxtjs/axios
nuxt.config.js
파일의 modules
에 모듈을 등록한다. 여기에 등록된 모듈은 인스턴스 속성으로 처리되므로 this.$axios와 같이 사용이 가능하다.
...
module.exports = {
...
modules: [
'@nuxtjs/axios',
],
...
axios: {
// 모듈 설정
baseURL: process.env.BASE_URL || 'your api server url'
}
...
}
nuxtServerInit
메서드와 actions
메서드의 사용법이 조금 다르기 때문에 아래 예제 코드를 잘 확인할 필요가 있다. 컴포넌트의 asyncData
메서드에서의 사용법은 nuxtServerInit
메서드와 동일하다.
import Vuex from 'vuex'
// 환경 설정을 통해 모듈 등록을 했으므로 추가로 axios 모듈을 import할 필요는 없다.
const createStore = () => {
return new Vuex.Store({
sate: { loadedPosts: [] },
mutations: {
// ...
},
actions: {
async nuxtServerInit({ commit }, { app }) {
try {
// nuxtServerInit 에서는 axios.get() -> app.$asxios.$get() 을 사용하고
// nuxt.config.js에 BASE_URL을 설정했기 때문에 상대 경로만 설정하면 되고
// 결과는 데이터만 추출되기 때문에 Data를 바로 사용할 수 있다.
const data = await app.$axios.$get('/posts.json')
const postsList = []
for (let key in data) {
postsList.push({ ...data[key], id: key })
}
} catch (e) {
console.error(e)
}
},
setPosts({ commit }, posts) { commit('setPosts', posts) },
createPost({ commit }, createdPost) {
createdPost.createdDate = new Date().toLocaleString();
createdPost.updatedDate = createdPost.createdDate
// actions 메서드 내부에서는 this.$axios를 사용하고
// BASE_URL 설정에 따라서 상대 경로만 설정하고
// data 바로 사용
return this.$axios.$post('posts.json', createdPost)
.then(data => {
commit('createPost', { ...createdPost, id: data.name })
})
.catch(e => console.error(e))
},
updatePost({ commit }, updatedPost) {
updatePost.updatedDate = new Date().toLocaleString()
// actions 메서드 내부에서는 this.$axios를 사용하고
// BASE_URL 설정에 따라서 상대 경로만 설정하고
// data 바로 사용
return this.$axios.$put('/posts/${updatedPost.id}.json', updatedPost)
.then(data => {
commit('updatePost', updatedPost)
})
.catch(e => console.error(e))
}
},
getters: {
loadedPosts(state) { return this.loadedPosts }
}
})
}
export default createStore
Axios는 Proxy 옵션을 제공하고 있다. 옵션에 대한 자세한 내용을 참고하로도록 한다.
우선 nuxt.config.ts 파일에 axios를 모듈로 등록해 줘야 옵션을 쉽게 설정하고 사용할 수 있다.
...
modules: [
"@nuxtjs/axios"
]
...
axios: {
proxy: true // default: false, boolean or object 설정 가능
baseURL: ....
credenital: true,
debug: true,
retry: {
retries: 3
},
requestInterceptor: (config, {stroe}) => {
config.headers.common['Authentication'] = ...
config.headers.common["Content-Type'] = ...
return config
}
}
...
proxy: {
'/api/': {
target: 'http://your.apiserver.com',
pathRewrite: { '^/api:': ''},
chagneOrigin: false,
prependPath: false
}
'/api2/': {
target: 'http://another.apiserver.com',
...
}
...
}
...
기본적인 설정 방법은 위와 같이 처리를 하면 되고 실제로 사용할 때는 proxy로 지정한 서버의 식별자를 이용해서 처리하면 된다.