1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue 3 + AxiosでREST APIを呼び出す方法

Posted at

Vue 3 + AxiosでREST APIを呼び出す方法

REST APIの仕組みがわかったら、次は実際に呼び出してデータを使ってみましょう!この記事では、Vue 3 と HTTP クライアント「Axios」を使って、外部のREST APIからデータを取得・表示する方法を解説します。


目次

  1. 前提環境
  2. Axiosとは?
  3. Vueでの実装ステップ
  4. GETリクエストの例
  5. POSTリクエストの例
  6. エラーハンドリング
  7. まとめ

前提環境

  • Vue 3 プロジェクトが作成済み(ViteやVue CLIでOK)
  • Composition API(<script setup>)を使用
  • axios がインストールされている
npm install axios

Axiosとは?

Axios は、HTTP通信を簡単に行うための JavaScript ライブラリです。標準の fetch() よりも書きやすく、デフォルト設定やレスポンスの処理が便利なのが特長です。

import axios from 'axios';

axios.get('https://api.example.com/users')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

Vueでの実装ステップ

  1. ref で状態(データ)を定義
  2. onMounted() で初回読み込み時にデータ取得
  3. テンプレートに表示

GETリクエストの例

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const users = ref([]);

onMounted(async () => {
  try {
    const res = await axios.get('https://jsonplaceholder.typicode.com/users');
    users.value = res.data;
  } catch (err) {
    console.error('取得失敗:', err);
  }
});
</script>

<template>
  <h2>ユーザー一覧</h2>
  <ul>
    <li v-for="user in users" :key="user.id">
      {{ user.name }} - {{ user.email }}
    </li>
  </ul>
</template>

POSTリクエストの例

import axios from 'axios';

const createUser = async () => {
  try {
    const res = await axios.post('https://jsonplaceholder.typicode.com/users', {
      name: 'New User',
      email: 'new@example.com'
    });
    console.log('作成されたユーザー:', res.data);
  } catch (err) {
    console.error('作成失敗:', err);
  }
};
  • axios.post(url, データ) で簡潔にPOST可能
  • ヘッダーに Content-Type を指定しなくても自動で付けてくれる

エラーハンドリング

Axiosはエラーを catch() または try-catch で受け取れます。

try {
  const res = await axios.get('/api/some-data');
  // 成功時処理
} catch (error) {
  if (error.response) {
    console.error('サーバー応答エラー:', error.response.data);
  } else if (error.request) {
    console.error('リクエストは送信されたが応答なし');
  } else {
    console.error('その他のエラー:', error.message);
  }
}

まとめ

  • Axiosは fetch よりも便利で人気が高い
  • Vue 3 との相性もよく、非同期処理も簡単に書ける
  • GET, POST, PUT, DELETE など柔軟に対応可能
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?