Back

Node.jsでAxiosを使用する方法(コード例付き)

Node.jsでAxiosを使用する方法(コード例付き)

AxiosはNode.jsでHTTPリクエストを簡素化するPromiseベースのHTTPクライアントです。GET・POSTリクエストの送信、レスポンスの処理、エラー管理などのタスクを合理化します。このガイドでは、実用的なコード例を交えながら、Node.jsでAxiosを使用する方法を探っていきます。

重要なポイント

  • AxiosはNode.jsでHTTPリクエストを行うシンプルなAPIを提供します。
  • 非同期コードをよりクリーンにするためにPromiseを利用しています。
  • さまざまなエラーシナリオを処理するための簡単なメカニズムを提供しています。

Node.jsでのAxiosのセットアップ

Node.jsプロジェクトでAxiosを使い始めるには:

  1. プロジェクトの初期化(まだの場合):

    npm init -y
    
  2. Axiosのインストール:

    npm install axios
    
  3. アプリケーションでAxiosを要求:

    const axios = require('axios');
    

GETリクエストの実行

GETリクエストは、指定されたエンドポイントからデータを取得します。Axiosを使用してGETリクエストを実行する方法は次のとおりです:

const axios = require('axios');

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

fetchData();

説明:

  • 非同期関数 fetchData を定義します。
  • await を使用してAxiosのGETリクエストを行います。
  • レスポンスデータをコンソールに出力します。
  • try...catch を使用してエラーを処理します。

POSTリクエストの実行

POSTリクエストは、新しいリソースを作成するためにサーバーにデータを送信します。POSTリクエストを実行する方法は次のとおりです:

const axios = require('axios');

async function createPost() {
  try {
    const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {
      title: 'New Post',
      body: 'This is the content of the new post.',
      userId: 1,
    });
    console.log('Post created:', response.data);
  } catch (error) {
    console.error('Error creating post:', error);
  }
}

createPost();

説明:

  • 非同期関数 createPost を定義します。
  • axios.post() でエンドポイントとデータオブジェクトを渡し、await を使用します。
  • 新しく作成された投稿を出力します。
  • エラーを適切に処理します。

レスポンスとエラーの処理

Axiosは、レスポンスとエラーを処理するための構造化された方法を提供します。レスポンスオブジェクトには、datastatusheadersなどのプロパティが含まれます。

さまざまなタイプのエラーを処理する方法は次のとおりです:

const axios = require('axios');

async function fetchData() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
    console.log('Data:', response.data);
    console.log('Status:', response.status);
  } catch (error) {
    if (error.response) {
      // サーバーが2xx以外のステータスコードで応答した
      console.error('Error data:', error.response.data);
      console.error('Error status:', error.response.status);
    } else if (error.request) {
      // レスポンスが受信されなかった
      console.error('No response received:', error.request);
    } else {
      // リクエストのセットアップ時のエラー
      console.error('Error:', error.message);
    }
  }
}

fetchData();

説明:

  • 成功時にレスポンスデータとステータスを出力します。
  • 以下のエラーを区別します:
    • レスポンスを伴うエラー (error.response)
    • レスポンスのないエラー (error.request)
    • その他のAxios関連のエラー (error.message)

よくある質問

はい、Axiosは isomorphic であり、両方の環境で実行できます。

Axiosは、リクエストとレスポンスの両方でJSONデータを自動的に変換するため、手動での解析が不要になります。

はい、リクエスト設定で `headers` オブジェクトを渡すことで、カスタムヘッダーを設定できます。

結論

Axiosは、明確で簡潔なAPIを提供することで、Node.jsでのHTTPリクエストを簡素化します。Promiseをサポートしているため、非同期操作を効率的に処理できます。GETリクエストとPOSTリクエストの実行方法、およびレスポンスとエラーの処理方法を理解することで、Node.jsアプリケーションにAxiosを効果的に統合できます。

Listen to your bugs 🧘, with OpenReplay

See how users use your app and resolve issues fast.
Loved by thousands of developers