웹사이트 검색

Axios로 Vue.js REST API 소비를 구성하는 방법


소개

Vue 2.0에서 개발자는 내장 HTTP 클라이언트 모듈이 다소 중복되고 타사 라이브러리에서 더 나은 서비스를 제공할 수 있다고 결정했습니다. 가장 자주 권장되는 대안은 Axios입니다.

Axios는 HTTP 클라이언트 라이브러리입니다. 기본적으로 약속을 사용하고 클라이언트와 서버 모두에서 실행되므로 서버 측 렌더링 중에 데이터를 가져오는 데 적합합니다. 약속을 사용하기 때문에 async/await와 결합하여 간결하고 사용하기 쉬운 API를 얻을 수 있습니다.

이 기사에서는 데이터 채우기 및 데이터 푸시와 관련된 작업을 위해 Vue.js 프로젝트에 Axios를 추가하는 방법을 살펴봅니다. 재사용 가능한 기본 인스턴스를 만드는 방법도 알아봅니다.

전제 조건

이 문서를 따라 하려면 다음이 필요합니다.

  • Node.js를 로컬에 설치했습니다. Node.js를 설치하고 로컬 개발 환경을 만드는 방법에 따라 수행할 수 있습니다.

액시오스 설치 및 가져오기

시작하려면 Axios를 설치해야 합니다.

npm으로 Axios를 설치할 수 있습니다.

  1. npm install axios --save

또는 원사로:

  1. yarn add axios

Vue.js 프로젝트에 Axios를 추가할 때 가져오기를 원할 것입니다.

import axios from 'axios';

다음으로 axios.get()을 사용하여 GET 요청을 수행합니다.

GET 요청으로 데이터 채우기

구성 요소에서 직접 Axios를 사용하여 메서드 또는 수명 주기 후크에서 데이터를 가져올 수 있습니다.

<template>
  <div>
    <ul v-if="posts && posts.length">
      <li v-for="post of posts">
        <p><strong>{{post.title}}</strong></p>
        <p>{{post.body}}</p>
      </li>
    </ul>

    <ul v-if="errors && errors.length">
      <li v-for="error of errors">
        {{error.message}}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  // Fetches posts when the component is created.
  created() {
    axios.get(`http://jsonplaceholder.typicode.com/posts`)
    .then(response => {
      // JSON responses are automatically parsed.
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

async/await 버전은 다음과 같습니다.

<!-- ... template code ... -->

<script>
import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  // Fetches posts when the component is created.
  async created() {
    try {
      const response = await axios.get(`http://jsonplaceholder.typicode.com/posts`)
      this.posts = response.data
    } catch (e) {
      this.errors.push(e)
    }
  }
}
</script>

이 코드는 JSONPlaceholder에서 \posts\를 검색하고 정렬되지 않은 목록을 \posts\로 채웁니다. 발생한 모든 \오류\는 순서가 지정되지 않은 별도의 목록에 나타납니다.

다음으로 axios.post()를 사용하여 POST 요청을 수행합니다.

POST 요청으로 데이터 푸시

Axios를 사용하여 POST, PUT, PATCHDELETE 요청을 보낼 수 있습니다.

참고: 모든 입력 이벤트에 대해 요청을 보내지 않을 것입니다. 스로틀링 또는 디바운싱 사용을 고려하십시오.

<template>
  <div>
    <input type="text" v-model="postBody" @change="postPost()" />
    <ul v-if="errors && errors.length">
      <li v-for="error of errors">
        {{error.message}}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      postBody: '',
      errors: []
    }
  },

  methods: {
    // Pushes posts to the server when called.
    postPost() {
      axios.post(`http://jsonplaceholder.typicode.com/posts`, {
        body: this.postBody
      })
      .then(response => {})
      .catch(e => {
        this.errors.push(e)
      })
    }
  }
}
</script>

async/await 버전은 다음과 같습니다.

<!-- ... template code ... -->

<script>
import axios from 'axios';

export default {
  data() {
    return {
      postBody: '',
      errors: []
    }
  },

  methods: {
    // Pushes posts to the server when called.
    async postPost() {
      try {
        await axios.post(`http://jsonplaceholder.typicode.com/posts`, {
          body: this.postBody
        })
      } catch (e) {
        this.errors.push(e)
      }
    }
  }
}
</script>

이 코드는 JSONPlaceholder에 콘텐츠를 제출할 입력 필드를 만듭니다. 발생한 모든 오류는 정렬되지 않은 목록에 나타납니다.

다음으로 axios.create()를 사용하여 기본 인스턴스를 만듭니다.

공통 기본 인스턴스 생성

자주 간과되지만 Axios가 제공하는 매우 유용한 기능은 인스턴스에 대한 모든 호출에서 공통 기본 URL 및 구성을 공유할 수 있는 기본 인스턴스를 생성하는 기능입니다. 이는 모든 호출이 특정 서버에 대한 것이거나 Authorization 헤더와 같은 헤더를 공유해야 하는 경우 유용합니다.

import axios from 'axios';

export const HTTP = axios.create({
  baseURL: `http://jsonplaceholder.typicode.com/`,
  headers: {
    Authorization: 'Bearer {token}'
  }
})

이제 구성 요소에서 HTTP를 사용할 수 있습니다.

<template>
  <div>
    <ul v-if="posts && posts.length">
      <li v-for="post of posts">
        <p><strong>{{post.title}}</strong></p>
        <p>{{post.body}}</p>
      </li>
    </ul>

    <ul v-if="errors && errors.length">
      <li v-for="error of errors">
        {{error.message}}
      </li>
    </ul>
  </div>
</template>

<script>
import { HTTP } from './http-common';

export default {
  data() {
    return {
      posts: [],
      errors: []
    }
  },

  created() {
    HTTP.get(`posts`)
    .then(response => {
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>

이 코드는 http-common.js에 설정된 구성을 사용하고 Authorization 헤더를 사용하여 JSONPlaceholder에 연결합니다. 게시물을 검색하고 오류를 포착합니다.

결론

이 기사에서는 Axios를 사용하여 데이터를 채우고 데이터를 푸시하는 방법을 소개했습니다. 또한 재사용 가능한 기본 인스턴스를 만드는 방법도 있습니다. 이는 Axios가 할 수 있는 일의 일부일 뿐입니다.

Axios에 대한 자세한 정보 및 문서를 보려면 GitHub 리포지토리를 방문하십시오.

Vue.js에 대해 자세히 알아보려면 연습 및 프로그래밍 프로젝트에 대한 Vue.js 주제 페이지를 확인하세요.