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

原生微信小程序网络请求与上传接口封装实战指南

本文基于微信小程序原生 API,封装 requestuploadFile 接口,最终实现统一请求管理、请求拦截、错误处理等能力。


📦 一、为什么要封装网络请求?

微信小程序提供了 wx.requestwx.uploadFile 原生 API,但直接使用存在以下问题:

  • 重复代码多:每次都要写 header、拼接 URL、处理 loading、异常等;
  • 缺少统一错误处理:每个请求都得自己 try-catch;
  • 不好管理 token 等公共逻辑:无法统一加请求头;
  • 调试困难:没有统一日志输出或接口追踪;

封装后,我们可以统一管理所有接口请求,提升开发效率与代码可维护性。


🏗️ 二、项目结构建议

/utils├── request.ts        # 通用网络请求封装├── upload.ts         # 上传封装└── config.ts         # 环境配置

⚙️ 三、基础配置 config.ts

// utils/config.tsexport const BASE_URL = 'https://api.example.com';export const DEFAULT_HEADER = {'Content-Type': 'application/json',
};export function getToken(): string {// 假设从本地获取缓存 tokenreturn wx.getStorageSync('token') || '';
}

🌐 四、封装通用 request 请求 request.ts

// utils/request.tsimport { BASE_URL, DEFAULT_HEADER, getToken } from './config';interface RequestOptions<T> {url: string;method?: 'GET' | 'POST' | 'PUT' | 'DELETE';data?: any;header?: Record<string, string>;showLoading?: boolean;timeout?: number;
}export function request<T = any>(options: RequestOptions<T>): Promise<T> {const {url,method = 'GET',data = {},header = {},showLoading = true,timeout = 10000,} = options;return new Promise((resolve, reject) => {if (showLoading) {wx.showLoading({ title: '加载中...', mask: true });}wx.request({url: BASE_URL + url,method,data,header: {...DEFAULT_HEADER,...header,Authorization: `Bearer ${getToken()}`, // 添加 token},timeout,success(res) {if (res.statusCode === 200) {resolve(res.data);} else {wx.showToast({ title: `错误 ${res.statusCode}`, icon: 'none' });reject(res);}},fail(err) {wx.showToast({ title: '网络异常', icon: 'none' });reject(err);},complete() {if (showLoading) {wx.hideLoading();}},});});
}

🖼️ 五、上传封装 upload.ts

// utils/upload.tsimport { BASE_URL, getToken } from './config';export interface UploadFileOptions {url: string;filePath: string;name?: string;formData?: Record<string, string>;showLoading?: boolean;
}export function uploadFile(options: UploadFileOptions): Promise<any> {const {url,filePath,name = 'file',formData = {},showLoading = true,} = options;return new Promise((resolve, reject) => {if (showLoading) {wx.showLoading({ title: '上传中...', mask: true });}wx.uploadFile({url: BASE_URL + url,filePath,name,formData,header: {Authorization: `Bearer ${getToken()}`,},success(res) {if (res.statusCode === 200) {try {resolve(JSON.parse(res.data)); // 注意返回是字符串} catch (e) {reject(e);}} else {wx.showToast({ title: '上传失败', icon: 'none' });reject(res);}},fail(err) {wx.showToast({ title: '上传异常', icon: 'none' });reject(err);},complete() {if (showLoading) {wx.hideLoading();}},});});
}

✅ 六、实际使用案例

示例:获取用户信息

// pages/user/index.tsimport { request } from '../../utils/request';Page({onLoad() {request({url: '/user/info',method: 'GET',}).then((res) => {console.log('用户信息', res);}).catch(console.error);},
});

示例:上传头像

// pages/upload/index.tsimport { uploadFile } from '../../utils/upload';Page({uploadAvatar() {wx.chooseImage({count: 1,success: (res) => {const filePath = res.tempFilePaths[0];uploadFile({url: '/upload/avatar',filePath,}).then((res) => {console.log('上传成功', res);}).catch(console.error);},});},
});

📚 七、总结

通过本教程,我们实现了小程序中通用的 requestuploadFile 的封装,具备了:

  • ✅ 支持 token 自动注入
  • ✅ 支持 loading 提示与关闭
  • ✅ 支持统一错误提示
  • ✅ 支持上传功能
  • ✅ 接口调用代码更清晰简洁
http://www.lryc.cn/news/574322.html

相关文章:

  • 【DeepSeek实战】2、DeepSeek特训:Function Calling与ReAct双引擎驱动大模型智能升级实战指南
  • 《高等数学》(同济大学·第7版)第六章 定积分的应用 第一节定积分的元素法
  • matlab实现大地电磁二维正演
  • 音视频全链路开发实践:基于SmartMediakit的架构设计与应用实战
  • Recent Advances in Speech Language Models: A Survey
  • 通信网络编程3.0——JAVA
  • 【信创-k8s】银河麒麟V10国防版+鲲鹏/飞腾(arm64架构)在线/离线部署k8s1.30+kubesphere
  • fiddler+安卓模拟器,解决无网络、抓不到https问题
  • 网络安全之某cms的漏洞分析
  • 阿里云Elasticsearch生产环境误删数据恢复指南
  • 将RESP.app的备份数据转码成AnotherRedisDesktopManager的格式
  • 越南数学家吴宝珠恶搞式证明朗兰兹纲领
  • 基于SpringBoot + Vue 的网上拍卖系统
  • ESXi 8 相较于 ESXi 7 升级
  • 【C++】哈希表的实现(链地址法)
  • Linux切换中文输入法
  • SpringCloud系列(32)--使用Hystrix进行全局服务降级
  • STM32对接霍尔传感器
  • Vibe Coding - 使用cursor从PRD到TASK精准分解执行
  • 第十六届蓝桥杯C/C++程序设计研究生组国赛 国二
  • Vue按键事件
  • ​​根系杂种优势的分子解码:SPE基因互补与进化可塑性的协同效应​​
  • 电路图识图基础知识-塔式起重机控制电路识图与操作要点(三十五)
  • TestCafe 全解析:免费开源的 E2E 测试解决方案实战指南
  • libwebsockets编译
  • 优化提示词的常用技巧
  • 使用AI开发招聘网站(100天AI编程实验)
  • Matplotlib数据可视化入门:从基础图表到多图展示
  • 【AI 测试】测试用例设计:人工智能语言大模型性能测试用例设计
  • MySQL 慢查询日志与 Binlog 启用与故障排查实录