Frontend
vue 프로젝트에서 API 호출하기 (Vue 버전 2)
herojoon
2022. 4. 10. 17:25
반응형
목표
vue 프로젝트에서 API 호출을 위한 axios plugin을 설치하고, API를 호출해봅니다.
axios는 Http Call을 위한 기능을 제공해주는 npm plugin 입니다.
해보기
1. axios plugin 설치
- axios URL: https://www.npmjs.com/package/axios
# vue프로젝트에서 아래 명령어로 axios를 설치해줍니다.
npm i axios
2. vue 프로젝트에서 axios를 사용하기 위하여 main.js에 axios import하기
<파일 위치>

<추가 코드>
import axios from 'axios'
Vue.use(axios)

3. axios를 전역으로 사용하기 위해 설정
Vue.prototype.$axios = axios

4. vue component에서 axios를 이용해서 API 호출 해보기
<script>
export default {
name: 'BoardList',
data: function () {
return {
boardList: []
}
},
created: function () {
this.getList()
},
methods: {
getList: function () {
// axios를 이용하여 API 호출 (component 안에서 axios를 this.$axios로 사용할 수 있습니다.)
this.$axios.get('http://localhost:8080/api/board/list').then(response => {
console.log('### response: ' + JSON.stringify(response))
this.boardList = response.data
}).catch(error => {
console.log(error)
})
}
}
}
</script>
반응형