웹/Vue
axios 사용
송민준
2021. 3. 21. 01:06
axios/axios
Promise based HTTP client for the browser and node.js - axios/axios
github.com
axios란?
- axios는 브라우저, node.js 등을 위한 프로미스 기반의 http 비동기 통신 라이브러리임.
특징
- 프로미스 활용(es6+)
- 요청과 응답 데이터의 변형
- JSON형태로 자동 변경
간단 사용법
해당 프로젝트 경로로 이동 후 아래 명령어 입력
npm install axios
package.json과 package-lock이 업데이트 됨.
코드 구조
<template>
<div>
Home
<div>
Board List :
<div v-if="loading">Loading...</div>
<div v-else>
Api result: {{boards}}
</div>
<ul>
<li>
<router-link to ="/b/1">Board 1</router-link>
</li>
<li>
<router-link to ="/b/2">Board 1</router-link>
</li>
</ul>
</div>
</div>
</template>
<script>
// axios 라이브러리 import
import axios from 'axios'
export default {
data() {
return {
loading: false,
boards: []
}
},
created() {
this.fetchData()
},
methods: {
fetchData() {
this.loading= true
// 프로미스 기반의 axios -> then, catch로 받음
axios.get('http://localhost:3000/boards')
.then(res => {
this.boards = res.data
})
.catch(res => {
this.$router.replace('/login')
})
.finally(() => {
this.loading= false
})
// const req = new XMLHttpRequest()
//
// req.open('GET','http://localhost:3000/health')
//
// req.send()
//
// req.addEventListener('load', () => {
// this.loading= false
// this.apiRes = {
// status: req.status,
// statusText: req.statusText,
// response: JSON.parse(req.response)
// }
// })
}
}
}
</script>
<style scoped>
</style>