封装的Ajax请求及使用

67 阅读1分钟
function ajaxRequest(url, method = 'GET', data = null, options = {}) {
  // 声明全局的基地址
  const BASE_URL = 'http://127.0.0.1:8081/';
  // 拼接完整的请求URL
  const fullUrl = `${BASE_URL}${url}`;

  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
    },
    credentials: 'same-origin',
  };

  const mergedOptions = { ...defaultOptions, ...options };

  if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
    mergedOptions.body = JSON.stringify(data);
  }

  return fetch(fullUrl, {
    method,
    ...mergedOptions,
  })
    .then(response => {
      if (!response.status) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.indexOf('application/json') !== -1) {
        return response.json();
      } else {
        return response.text();
      }
    })
    .catch(error => {
      throw new Error(`Network error: ${error}`);
    });
}
module.exports = ajaxRequest;
// 使用示例

ajaxRequest('/your/api/endpoint', 'GET')
  .then(data => console.log('Received data:', data))
  .catch(error => console.error('Error:', error));