如何封装小程序的数据请求方法

平时我们在开发中也会封装数据请求的通用工具,因为有很多相同的处理,没必要每次使用都把重复的再写一遍。在微信小程序中也是一样,封装数据请求的方式可以提高代码的可维护性和复用性。

创建请求模块

首先,创建一个新的 JavaScript 文件(例如 api.js),用于封装所有的数据请求。这个模块将包含一个通用的请求方法和具体的 API 方法。

api.js:

const baseUrl = 'https://example.com/api'; // 替换为你的实际API地址

const request = (url, method, data, header = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseUrl}${url}`,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/json',
        ...header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

const get = (url, data, header) => {
  return request(url, 'GET', data, header);
};

const post = (url, data, header) => {
  return request(url, 'POST', data, header);
};

// 其他请求方法可以按需添加,例如 put、delete 等
const put = (url, data, header) => {
  return request(url, 'PUT', data, header);
};

const del = (url, data, header) => {
  return request(url, 'DELETE', data, header);
};

// 具体的 API 方法
const api = {
  getUserData: (userId) => get(`/user/${userId}`),
  updateUserData: (userId, data) => put(`/user/${userId}`, data),
  createUserData: (data) => post('/user', data),
  deleteUserData: (userId) => del(`/user/${userId}`)
};

export default api;

使用封装的请求模块

在需要进行数据请求的页面或组件中引入封装好的 api 模块,并调用其中的方法。

页面 A:

import api from '../../utils/api.js'; // 根据你的实际文件路径调整

Page({
  data: {
    userData: null,
  },
  onLoad: function () {
    this.fetchUserData();
  },
  fetchUserData: function () {
    const userId = 123; // 假设这是需要查询的用户ID
    api.getUserData(userId)
      .then(data => {
        this.setData({
          userData: data
        });
      })
      .catch(err => {
        console.error('请求失败', err);
      });
  }
});

错误处理与状态管理

为了增强请求模块的健壮性,可以进一步添加全局的错误处理和状态管理。例如,你可以在 request 函数中处理常见的 HTTP 错误状态码,或者在全局展示错误提示。

添加全局错误处理:

const handleErrors = (statusCode, data) => {
  switch (statusCode) {
    case 400:
      wx.showToast({ title: '请求错误', icon: 'none' });
      break;
    case 401:
      wx.showToast({ title: '未授权', icon: 'none' });
      break;
    case 404:
      wx.showToast({ title: '资源未找到', icon: 'none' });
      break;
    case 500:
      wx.showToast({ title: '服务器错误', icon: 'none' });
      break;
    default:
      wx.showToast({ title: '未知错误', icon: 'none' });
      break;
  }
};

const request = (url, method, data, header = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseUrl}${url}`,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/json',
        ...header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          handleErrors(res.statusCode, res.data);
          reject(res.data);
        }
      },
      fail: (err) => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        reject(err);
      }
    });
  });
};

通过这种方式,微信小程序的数据请求逻辑被封装在一个独立的模块中,使代码结构更加清晰,复用性更高,同时也便于集中管理和维护请求逻辑。

posted on 2024-06-04 14:09  温华从此不练剑  阅读(3)  评论(0编辑  收藏  举报