前端api(请求后端)简易template

微信小程序 API 模块模板

基本 API 模块结构

/**
 * 示例API模块
 */
const api = require('../api');
const config = require('../../config/index');

// 示例API对象
const exampleApi = {
  // API方法定义...
};

// 导出模块
module.exports = exampleApi;

标准 RESTful 请求方法

获取列表数据

/**
 * 获取列表数据
 * @param {Object} params - 查询参数
 * @param {boolean} showLoading - 是否显示加载提示
 * @returns {Promise} Promise对象
 */
getList: (params, showLoading = true) => {
  return api.get('/example/list', params, showLoading);
},

获取详情数据

/**
 * 获取详情数据
 * @param {string} id - 记录ID
 * @param {boolean} showLoading - 是否显示加载提示
 * @returns {Promise} Promise对象
 */
getDetail: (id, showLoading = true) => {
  return api.get(`/example/${id}`, {}, showLoading);
},

提交数据

/**
 * 提交数据
 * @param {Object} data - 提交的数据
 * @param {boolean} showLoading - 是否显示加载提示
 * @returns {Promise} Promise对象
 */
submit: (data, showLoading = true) => {
  return api.post('/example/submit', data, showLoading);
},

更新数据

/**
 * 更新数据
 * @param {string} id - 记录ID
 * @param {Object} data - 更新的数据
 * @param {boolean} showLoading - 是否显示加载提示
 * @returns {Promise} Promise对象
 */
update: (id, data, showLoading = true) => {
  return api.put(`/example/${id}`, data, showLoading);
},

删除数据

/**
 * 删除数据
 * @param {string} id - 记录ID
 * @param {boolean} showLoading - 是否显示加载提示
 * @returns {Promise} Promise对象
 */
delete: (id, showLoading = true) => {
  return api.delete(`/example/${id}`, {}, showLoading);
},

自定义请求方法

直接使用 wx.request 的请求

/**
 * 使用wx.request的直接请求示例
 * @param {Object} params - 请求参数
 * @param {boolean} showLoading - 是否显示加载提示
 * @returns {Promise} Promise对象
 */
customRequest: (params, showLoading = true) => {
  return new Promise((resolve, reject) => {
    // 获取token
    const token = wx.getStorageSync(config.TOKEN_KEY);
    
    if (showLoading) {
      wx.showLoading({
        title: '加载中',
        mask: true
      });
    }
    
    wx.request({
      url: `${config.HOST_URL}/example/custom`,
      method: 'GET',
      data: params || {},
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      success: (res) => {
        if (showLoading) {
          wx.hideLoading();
        }
        
        console.log('请求结果:', res.data);
        
        if (res.data && (res.data.code === 0 || res.data.code === 200)) {
          resolve(res.data);
        } else {
          console.error('请求失败:', res.data);
          reject({
            code: res.data?.code || -1,
            message: res.data?.message || '请求失败',
            data: res.data?.data || null
          });
        }
      },
      fail: (err) => {
        if (showLoading) {
          wx.hideLoading();
        }
        console.error('请求失败:', err);
        reject({
          code: -1,
          message: '网络请求失败',
          data: null
        });
      }
    });
  });
},

文件上传方法

/**
 * 上传文件示例
 * @param {string} filePath - 文件路径
 * @param {boolean} showLoading - 是否显示加载提示
 * @returns {Promise} Promise对象
 */
uploadFile: (filePath, showLoading = true) => {
  return new Promise((resolve, reject) => {
    if (!filePath) {
      reject({
        code: 400,
        message: '文件路径不能为空',
        data: null
      });
      return;
    }
    
    const token = wx.getStorageSync(config.TOKEN_KEY);
    
    if (showLoading) {
      wx.showLoading({
        title: '上传中',
        mask: true
      });
    }
    
    wx.uploadFile({
      url: `${config.HOST_URL}/example/upload`,
      filePath: filePath,
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      success: (res) => {
        if (showLoading) {
          wx.hideLoading();
        }
        
        let response;
        try {
          response = JSON.parse(res.data);
        } catch (e) {
          reject({
            code: -1,
            message: '解析响应失败',
            data: null
          });
          return;
        }
        
        if (response && (response.code === 0 || response.code === 200)) {
          resolve(response);
        } else {
          reject({
            code: response?.code || -1,
            message: response?.message || '上传失败',
            data: response?.data || null
          });
        }
      },
      fail: (err) => {
        if (showLoading) {
          wx.hideLoading();
        }
        reject({
          code: -1,
          message: '网络请求失败: ' + (err.errMsg || ''),
          data: null
        });
      }
    });
  });
}

使用说明

  1. 将模板复制到 api/modules/ 目录下的新文件中,例如 api/modules/example.js
  2. 修改模块名称、API路径和方法名称以适应你的需求
  3. api/index.js 中导入和导出你的新API模块:
// 导入新的API模块
const exampleApi = require('./modules/example');

module.exports = {
  // 已有的模块...
  exampleApi
};
  1. 在页面中使用API:
const { exampleApi } = require('../../api/index');

Page({
  data: {
    // 页面数据
  },
  
  onLoad: function() {
    this.loadData();
  },
  
  loadData: function() {
    exampleApi.getList()
      .then(res => {
        // 处理成功响应
        this.setData({
          list: res.data
        });
      })
      .catch(err => {
        // 处理错误
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  }
});
pleApi.getList()
      .then(res => {
        // 处理成功响应
        this.setData({
          list: res.data
        });
      })
      .catch(err => {
        // 处理错误
        wx.showToast({
          title: err.message,
          icon: 'none'
        });
      });
  }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值