当前位置: 首页 > 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'});});}
});
http://www.xdnf.cn/news/3997.html

相关文章:

  • Python高级爬虫之JS逆向+安卓逆向1.5节: 控制结构
  • docker harbor私有仓库登录报错
  • Ubuntu利用docker搭建Java相关环境问题记录
  • 如何有效防止服务器被攻击
  • 在激烈竞争下B端HMI设计怎样打造独特用户体验?
  • 数组理论基础
  • 从GPT到Gemini 大模型进化史
  • ADVB发送器设计
  • Matter如何终结智能家居生态割据,重构你的居住体验?
  • 随手笔记-python-opencv 读取图像的顺序 与pytorch处理图像的顺序
  • Mysql的安装
  • Java面试(2025)—— Spring
  • FPGA入门学习Day1——设计一个DDS信号发生器
  • opencv HSV的具体描述
  • 【Java学习笔记】关键字汇总
  • 赛灵思 XCVU440-2FLGA2892E XilinxFPGA Virtex UltraScale
  • ESP32- 开发笔记- 硬件设计-ESP32-C3 天线设计-利用嘉立创EDA来设计
  • 数码管LED显示屏矩阵驱动技术详解
  • Gitignore详解:版本控制中的文件忽略机制
  • 秒杀系统解决两个核心问题的思路方法总结:1.库存超卖问题;2.用户重复抢购问题。
  • Ubuntu 安装WPS Office
  • JavaScript 对象复制:浅拷贝与深拷贝
  • 观察者模式与发布订阅模式:解耦与通信的艺术
  • 【网络】IP层的重要知识
  • 【工具】视频翻译、配音、语音克隆于一体的一站式视频多语言转换工具~
  • Redis面试——事务
  • NoSQL 与 NewSQL 全面对比:如何选择适合你的数据库方案?
  • 使用代理IP提取数据的步骤是什么?代理IP如何提高爬虫采集效率?
  • 2000-2017年各省国有经济煤气生产和供应业固定资产投资数据
  • 从基础概念到前沿应用了解机器学习