0
0

FetchでPostするときの、headers部分を共用化する方法

Posted at

指定を繰り返すことなく、共通のオプションを利用する方法として、カスタムのHTTPクライアントやユーティリティ関数を作成して再利用することができます。以下にその一例を示します。

// utils/httpClient.ts

const BASE_URL = 'https://api.example.com';

export const postRequest = async (endpoint: string, data: any) => {
  const url = `${BASE_URL}/${endpoint}`;

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // 他に必要なヘッダーがあればここで指定
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    throw new Error(`Error in postRequest: ${error}`);
  }
};

上記の例では、postRequestという共通の関数を作成し、それを他のファイルで利用できるようにしています。この関数にはエンドポイントとデータを渡すことで、POSTリクエストを行えます。

使用する側では、この関数をインポートして使います。

// 他のファイルでの利用例

import { postRequest } from 'utils/httpClient';

async function postData() {
  const endpoint = 'post';
  const dataToSend = {
    key: 'value',
  };

  try {
    const data = await postRequest(endpoint, dataToSend);
    console.log('Data:', data);
  } catch (error) {
    console.error('Error posting data:', error);
  }
}

// 関数を呼び出し
postData();

このようにすることで、共通のオプションを1か所にまとめて再利用でき、コードを簡潔に保つことができます。

0
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
0
0