본문 바로가기
Programming/Vue.js

Vue.js에서 Axios를 이용한 비동기 통신

by 주리니e 2022. 12. 6.
728x90

Vue.js에서 Axios를 이용한 비동기 통신

 

Vue에서 권고하는 Promise 기반의 HTTP 라이브러리로서 웹 어플리케이션에서 서버와 HTTP 요청을 주고 받을 수 있다. 또 Promise를 사용하면 비동기식 처리 상에서 데이터가 넘어왔을 때만 해당 코드가 실행되도록 하는 콜백 처리를 해줄 수 있다. Axios 는 다음과 같은 기능을 제공한다.

  • 브라우저를 위해 XMLHttpRequests 생성
  • node.js를 위해 http 요청 생성
  • Promise API를 지원
  • 요청 및 응답 인터셉트
  • 요청 및 응답 데이터 변환
  • 요청 취소
  • JSON 데이터 자동 변환
  • XSRF를 막기위한 클라이언트 사이드 지원

 

  • 샘플 프로젝트 생성
> vue create axios-test

 

  • Axios 설치
> npm install axios

Axios를 설치하는 방법은 여러가지가 있는데 위 npm을 위한 방식 말고도 yarn, CDN 등 여러 방법이 있으니 맨 하단의 링크를 참조하자.

 

  • JSON 테스트용 데이터

Axios 테스트하기 위해 아래 사이트에서 제공하는 REST API를 통한 JSON 데이터를 가져온다.

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. As of Oct 2022, serving ~1.7 billion requests each month.

jsonplaceholder.typicode.com

https://jsonplaceholder.typicode.com/todos/1

 

  • App.vue
<template>
<button @click="get">데이터 가져오기</button>
<p>{{ data }}</p>
</template>
<script>
import axios from "axios";
export default {
name: "App",
data() {
return {
data: [],
id: 1,
};
},
methods: {
get() {
axios
.get(`https://jsonplaceholder.typicode.com/todos/${this.id}`)
.then((result) => {
console.log(result.data);
this.data.push(result.data);
this.id++;
})
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log("finally");
});
},
},
};
</script>
<style></style>
> npm run serve

위 코드는 data라는 배열에 '데이터 가져오기' 버튼을 클릭할 때마다 Axios 라이브러리를 이용하여 위 API를 호출해 데이터를 가져와 화면에 출력하는 샘플 소스코드이다. 

 

 

  • axios.get()
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then((result) => {
// 성공 시 실행할 코드
})
.catch((error) => {
// 에러 발생 시 실행될 코드
})
.finally(() => {
// 성공/실패 여부 상관없이 마지막으로 실행 될 코드
});

 

  • axios.post() 
axios.post('url', {userId : 2, id : 1, title : 'jiurinie', completed : true })
.then((result) => {
// 성공 시 실행할 코드
})
.catch((error) => {
// 에러 발생 시 실행될 코드
})
.finally(() => {
// 성공/실패 여부 상관없이 마지막으로 실행 될 코드
});

 

  • Axios Docs
 

시작하기 | Axios Docs

시작하기 브라우저와 node.js에서 사용할 수 있는 Promise 기반 HTTP 클라이언트 라이브러리 Axios란? Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 입니다. 그것은 동형 입니다(동일한 코

axios-http.com

728x90

댓글