欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > 前端api(请求后端)简易template

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

2025/4/22 0:53:01 来源:https://blog.csdn.net/m0_64098720/article/details/147311226  浏览:    关键词:前端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'});});}
});

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词