Frontend/Vue.js

[Vue CLI] axios 사용하기

gamzaggang7 2024. 5. 27. 23:33
728x90

axios는 HTTP 요청을 보내기 위한 라이브러리로, Vue에서 비동기 통신을 쉽게 처리할 수 있다.

 

axios API

  • axios.get('url').then().catch(): 해당 url 주소에 대해 HTTP GET 요청을 보낸다. 서버에서 보낸 데이터를 정상적으로 받아오면 then() 안에 정의한 로직이 실행되고, 데이터를 밥아올 때 오류가 발생하면 catch()에 정의한 로직이 수행된다.
  • axios.post('url').then().catch(): 해당 url 주소에 대해 HTTP POST 요청을 보낸다. then()고 catch()의 동작은 위와 같다.
  • axios{( 옵션 속성 )}: HTTP 요청에 대한 자세한 속성들을 직접 정의하여 보낼 수 있다. 데이터 요청을 보낼 URL, HTTP 요청 방식, 보내는 데이터 유형 등

 

설치

npm install axios

 

사용 예

main.js

axios를 전역으로 설정할 수 있다.

import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'

const app = createApp(App)

app.config.globalProperties.$axios = axios

app.mount('#app')

 

728x90

App.vue

<template>
  <h1>Axios Example</h1>
  <button @click="fetchData">Fetch Data GET</button>
  <button @click="sendData">Send Data with POST</button>
  <button @click="makeRequest">Make Custom Request</button>

  <div v-if="responseData">
    <h2>response Data:</h2>
    <pre>{{ responseData }}</pre>
  </div>
</template>

<script>
import axios from "axios";
import { ref } from "vue";

export default {
  name: "AxiosExample",
  setup() {
    const responseData = ref(null);

    const fetchData = async () => {
      try {
        const response = await axios.get(
        );
        responseData.value = response.data;
      } catch (error) {
        console.error(error);
      }
    };

    const sendData = async () => {
      try {
        const response = await axios.post(
          {
            title: "foo",
            body: "bar",
            userId: 1,
          }
        );
        responseData.value = response.data;
      } catch (error) {
        console.error(error);
      }
    };

    const makeRequest = async () => {
      try {
        const response = await axios({
          method: "get",
          headers: {
            "Content-Type": "application/json",
          },
        });
        responseData.value = response.data;
      } catch (error) {
        console.error(error);
      }
    };

    return {
      fetchData,
      sendData,
      makeRequest,
      responseData,
    };
  },
};
</script>

<style>
button {
  display: block;
  margin-bottom: 10px;
}
</style>
  • template
    • 각 버튼은 클릭 이벤트에 반응하여 컴포넌트의 메서드(get, post, 커스텀 요청)을 수행한다.
    • v-if 디렉티브를 사용하여 responseData가 존재할 때만 해당 div를 렌더링한다. 즉 서버로부터 응답 데이터를 받아왔을 때만 이 부분이 화면에 보인다.
  • script
    • GET 요청 (fetchData): axios.get을 사용해 지정된 url에서 데이터를 가져온다. 성공적으로 가져오면 responseData 변수에 저장한다.
    • POST 요청 (sendData): axios.post를 사용해 데이터를 서버에 전송한다. 전송할 데이터는 title, body, userId 필드를 포함한 객체이다. 성공적으로 데이터를 전송하면 responseData 변수에 응답 데이터를 저장한다.
    • 일반 요청 (makeRequest): axios 함수를 직접 호출하여 요청을 수행한다. 메서드, url, 헤더 등을 직접 설정할 수 있다. 여기서는 GET 요청을 수행하며 성공 시 responseData 변수에 응답 데이터를 저장한다.
  • 위 url은 JSONPlaceholder라는 무료 온라인 REST API 엔드포인트이다. 테스트와 프로토타이핑을 위해 가짜 데이터를 제공하는 무료 서비스다.

결과)

728x90