banner
leoking

leoking

前端开发者
tg_channel

Fetch API のラッパー

使用 JavaScript 的 Fetch API 封装的公共请求文件示例。この例には、POST、GET、PUT などのリクエストメソッドが含まれています。プロジェクトの要件に応じて適切な調整を行う必要があることに注意してください。

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

const handleResponse = async (response) => {
  if (response.ok) {
    const data = await response.json();
    return data;
  } else {
    const error = await response.text();
    throw new Error(error);
  }
};

const request = async (url, options) => {
  try {
    const response = await fetch(`${BASE_URL}${url}`, options);
    const data = await handleResponse(response);
    return data;
  } catch (error) {
    console.error('リクエストが失敗しました:', error);
    throw error;
  }
};

export const get = (url, headers = {}) => {
  const options = {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      ...headers,
    },
  };
  return request(url, options);
};

export const post = (url, body, headers = {}) => {
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...headers,
    },
    body: JSON.stringify(body),
  };
  return request(url, options);
};

export const put = (url, body, headers = {}) => {
  const options = {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      ...headers,
    },
    body: JSON.stringify(body),
  };
  return request(url, options);
};

export const del = (url, headers = {}) => {
  const options = {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json',
      ...headers,
    },
  };
  return request(url, options);
};

この封装されたリクエストファイルを使用すると、プロジェクトで簡単に GET、POST、PUT などのリクエストを行うことができます。例:

import * as request from './request';

// GET リクエストの例
request.get('/users')
  .then(data => console.log(data))
  .catch(error => console.error(error));

// POST リクエストの例
request.post('/users', { name: 'John Doe', age: 30 })
  .then(data => console.log(data))
  .catch(error => console.error(error));

// PUT リクエストの例
request.put('/users/1', { name: 'Jane Doe', age: 28 })
  .then(data => console.log(data))
  .catch(error => console.error(error));

// DELETE リクエストの例
request.del('/users/1')
  .then(data => console.log(data))
  .catch(error => console.error(error));

プロジェクトが Fetch API をサポートしていることを確認するか、polyfill(例:whatwg-fetch)を使用して古いブラウザをサポートするようにしてください。

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。