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)來增加對舊瀏覽器的支援。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。