当前位置: 首页 > 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 提示与关闭
  • ✅ 支持统一错误提示
  • ✅ 支持上传功能
  • ✅ 接口调用代码更清晰简洁

相关文章:

  • 黑马程序员苍穹外卖DAY1
  • Java 程序设计试题​
  • 拼多多API限流机制破解:分布式IP池搭建与流量伪装方案
  • 从 0 到 1 构建 Graph RAG 系统:本地图谱 + 通义千问落地实践
  • OVS Faucet练习(下)
  • matlab实现大地电磁二维正演
  • 吃透 Golang 基础:测试
  • C++语言发展历程-2025
  • Python实例题:基于区块链的去中心化应用平台(区块链、智能合约)
  • 京东金融API支付链路剖析:白条分期接口的安全加固方案
  • STM32对接霍尔传感器
  • 技术逐梦之旅:从C语言到Vue的成长之路
  • Java底层原理:深入理解JVM内存管理机制
  • 如何在 Python 中连接 Elasticsearch 并使用 Qwen3 来实现 RAG
  • Life:Internship in OnSea Day 1
  • 基于SpringBoot + Vue 的网上拍卖系统
  • SpringCloud系列(32)--使用Hystrix进行全局服务降级
  • 联合语音和文本机器翻译,支持多达100种语言(nature子刊论文研读)
  • [Python] 使用 dataclass 简化数据结构:定义、功能与实战
  • React Native【实用教程】(含图标方案,常用第三库,动画,内置组件,内置Hooks,内置API,自定义组件,创建项目等)
  • 全球网站开发者大会/磁力宅
  • 太原制作响应式网站/资源
  • 北京百度seo公司/seo综合查询中的具体内容有哪些
  • 高端女装/北京百度推广排名优化
  • 模版网站可以做排名嘛/百度ai搜索引擎
  • 网站开发项目详细计划书/建站为应用技术