AxiosでVue.jsRESTAPIの消費を構成する方法
序章
Vue 2.0では、開発者は、組み込みのHTTPクライアントモジュールを使用することはかなり冗長であり、サードパーティのライブラリによってより適切にサービスを提供できると判断しました。 最も頻繁に推奨される代替手段はAxiosです。
AxiosはHTTPクライアントライブラリです。 デフォルトではpromises
を使用し、クライアントとサーバーの両方で実行されるため、サーバー側のレンダリング中にデータをフェッチするのに適しています。 promises
を使用しているため、async
/ await
と組み合わせて、簡潔で使いやすいAPIを取得できます。
この記事では、データの入力とデータのプッシュを含むタスクのために、Vue.jsプロジェクトにAxiosを追加する方法について説明します。 また、再利用可能なベースインスタンスの作成についても学習します。
前提条件
この記事をフォローするには、次のものが必要です。
- Node.jsはローカルにインストールされます。これは、Node.jsのインストール方法とローカル開発環境の作成に従って実行できます。
インストールとインポートaxios
開始するには、Axiosをインストールする必要があります。
npmを使用してAxiosをインストールできます。
npm install axios --save
または糸で:
yarn add axios
AxiosをVue.jsプロジェクトに追加するときは、次のようにインポートする必要があります。
import axios from 'axios';
次に、axios.get()
を使用してGET
リクエストを作成します。
GET
リクエストをデータに入力する
コンポーネントでAxiosを直接使用して、メソッドまたはライフサイクルフックからデータをフェッチできます。
ExampleComponentGet.vue
<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
バージョンは次のようになります。
ExampleComponentGet.vue
<!-- ... 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"
を入力します。 検出された"errors"
は、別の順序付けされていないリストに表示されます。
次に、axios.post()
を使用してPOST
リクエストを作成します。
POST
リクエストでデータをプッシュする
Axiosを使用して、POST
、PUT
、PATCH
、およびDELETE
リクエストを送信できます。
注:すべての入力イベントでリクエストを送信する必要はありません。 スロットルまたはデバウンスの使用を検討してください。
ExampleComponentPost.vue
<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
バージョンは次のようになります。
ExampleComponentPost.vue
<!-- ... 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
ヘッダーなどのヘッダーを共有する必要がある場合に便利です。
http-common.js
import axios from 'axios'; export const HTTP = axios.create({ baseURL: `http://jsonplaceholder.typicode.com/`, headers: { Authorization: 'Bearer {token}' } })
これで、コンポーネントでHTTP
を使用できます。
ExampleComponentBase.vue
<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に接続します。 posts
を取得し、エラーをキャッチします。
結論
この記事では、Axiosを使用してデータを入力およびプッシュする方法を紹介しました。 また、再利用可能なベースインスタンスを作成する方法もあります。 これは、Axiosでできることのほんの一部にすぎません。
Axiosの詳細とドキュメントについては、GitHubリポジトリにアクセスしてください。
Vue.jsの詳細については、Vue.jsトピックページで演習とプログラミングプロジェクトを確認してください。