当前位置: 首页 > news >正文

前端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) => {// 获取tokenconst 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'});});}
});

相关文章:

  • 多模态模型 Grounding DINO 初识
  • HFSS(李明洋)学习记录1
  • 算法:双指针(快慢指针|对撞指针)、快排、模拟、二分、贪心
  • 4月17号
  • Ubuntu利用docker搭建Java相关环境问题记录
  • 影视产业链中的律师角色以及合规风控要点
  • Electricity Market Optimization 探索系列(VII)- 直流潮流方程的推导及例题
  • 自然语言处理(NLP)领域大图
  • 速盾:高防CDN访问多了会影响源站吗?
  • 闭坑-- `a-auto-complete` 组件中的 `options` 数据存在重复
  • STM32 F103 标准库CH452A 4线 数码管驱动芯片显示数码管
  • LVS+Keepalived+dns高可用项目架构
  • Obsidian无门槛简明教程
  • 写项目时一些疑惑:组件间的通信、createDownloadUrl和DownloadUrl,ArrayBuffer与Blob等
  • C++十进制与十六进制
  • 20个常用的初级Java笔试题及其参考答案
  • 这几天调试VR,几个渲染效果不错
  • 【随身WIFI】随身WiFi Debian系统优化教程
  • Sql刷题日志(day3)
  • Vue基础(5)_事件修饰符
  • 特朗普的百日执政支持率与他“一税解千愁”的世界观和方法论
  • 澎湃思想周报丨数字时代的育儿;凛冬已至好莱坞
  • 人社部:对个人加大就业补贴支持,对企业加大扩岗支持
  • 全过程人民民主研究基地揭牌,为推动我国民主政治建设贡献上海智慧
  • 上海超万套保租房供应高校毕业生,各项目免押、打折等优惠频出
  • 杭州打造商业航天全产业链,请看《浪尖周报》第22期