TypeScriptを使用してWeb開発を行う際、HTTPリクエストを簡単かつ効果的に行う方法が求められます。その中で、axiosは非常に人気のあるHTTPクライアントライブラリの一つです。本記事では、TypeScriptプロジェクトでaxiosを使用する方法に焦点を当てます。

axiosとは

axiosはPromiseベースのHTTPクライアントであり、ブラウザとNode.jsの両方で利用できます。シンプルで直感的なAPIを提供し、さまざまなプラットフォームでのHTTP通信を容易にします。TypeScriptとの組み合わせは特に力強く、型安全性を確保しながらHTTPリクエストを処理できます。

インストール

まず最初に、axiosをインストールします。プロジェクトのルートディレクトリで以下のコマンドを実行します。

npm install axios

基本的な使い方

axiosを使用してGETリクエストを行う基本的な例を見てみましょう。

import axios from 'axios';

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchData();

POSTリクエスト

データをサーバーに送信するためのPOSTリクエストの例も見てみましょう。

import axios from 'axios';

async function postData() {
  try {
    const data = {
      key1: 'value1',
      key2: 'value2',
    };

    const response = await axios.post('https://api.example.com/post-endpoint', data);
    console.log(response.data);
  } catch (error) {
    console.error('Error posting data:', error);
  }
}

postData();

カスタム設定

axiosは様々なカスタマイズオプションを提供しています。例えば、タイムアウトの設定やヘッダーの追加などがあります。これにより、特定の要件に合わせてaxiosを調整できます。

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  headers: {'X-Custom-Header': 'value'},
});

async function fetchDataWithCustomSettings() {
  try {
    const response = await instance.get('/data');
    console.log(response.data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

fetchDataWithCustomSettings();

TypeScriptとaxiosの組み合わせは、型の恩恵を受けながら安全かつ効果的にHTTPリクエストを行うための素晴らしい選択肢です。以上が、TypeScriptでaxiosを使用する基本的な手順と例です。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です