banner
leoking

leoking

前端开发者
tg_channel

Fetch API Encapsulation

Example of a public request file wrapped with the Fetch API in JavaScript. This example includes request methods such as POST, GET, PUT, etc. Please note that you need to make corresponding adjustments according to your project requirements.

// 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('Request failed:', 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);
};

With this wrapped request file, you can easily make GET, POST, PUT, and other requests in your project. For example:

import * as request from './request';

// GET request example
request.get('/users')
  .then(data => console.log(data))
  .catch(error => console.error(error));

// POST request example
request.post('/users', { name: 'John Doe', age: 30 })
  .then(data => console.log(data))
  .catch(error => console.error(error));

// PUT request example
request.put('/users/1', { name: 'Jane Doe', age: 28 })
  .then(data => console.log(data))
  .catch(error => console.error(error));

// DELETE request example
request.del('/users/1')
  .then(data => console.log(data))
  .catch(error => console.error(error));

Please ensure that your project supports the Fetch API or use a polyfill (e.g., whatwg-fetch) to add support for older browsers.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.