原生微信小程序封装request

好长时间没有写原生小程序,特别是那个request请求,乱七八糟,已经完全不适用现代化开发。

因此手搓了一个TypeScript版的request,如下:

TypeScript 复制代码
// request.ts

// 定义请求头的类型
type Headers = {
  // 指定内容类型,可以是 'application/json' 或 'application/x-www-form-urlencoded'
  'Content-Type': 'application/json' | 'application/x-www-form-urlencoded';
  // 认证令牌
  'token': string;
};

// 定义请求配置接口
interface RequestConfig {
  // 请求的URL
  url: string;
  // 请求的数据,可以是字符串、对象或ArrayBuffer
  data: string | object | ArrayBuffer;
  // HTTP方法,支持多种请求类型
  method: "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT";
  // 可选的请求超时时间
  timeout?: number;
  // 可选的请求头
  header?: Headers;
}

// 请求拦截器,处理请求配置
const requestInterceptor = (config: RequestConfig) => {
  console.log(config)
  // 从本地存储中获取token
  const token = wx.getStorageSync("token") || "";
  if(!config.header) config.header = { 'Content-Type': 'application/json', token};
  // 返回处理后的请求配置
  return config;
};

// 发起请求的函数
const request = (
  // 请求的URL
  url: string,
  // 请求的数据,可以是字符串、对象或ArrayBuffer
  data: string | object | ArrayBuffer,
  // 请求的方法,使用RequestConfig接口中的method类型
  method: RequestConfig['method'],
  // 可选的请求头,使用Headers类型
  header?: Headers,
  // 可选的请求超时时间
  timeout?: number,
) => {
  // 返回一个Promise对象,用于处理异步请求
  return new Promise((resolve, reject) => {
    // 使用请求拦截器处理请求配置
    const interceptedConfig = requestInterceptor({
      url,
      method,
      data,
      header,
      timeout,
    });
    // 发起wx.request请求
    wx.request({
      // 展开处理后的请求配置
      ...interceptedConfig,
      // 设置请求超时时间为5000毫秒
      timeout: 5000,
      // 请求成功的回调函数
      success: (res) => {
        // 如果状态码为200,解析数据并解决Promise
        if (res.statusCode === 200) resolve(res.data);
        // 否则,拒绝Promise并返回错误
        else reject(new Error(res.statusCode.toString()));
      },
      // 请求失败的回调函数,拒绝Promise并返回错误
      fail: (err) => {
        console.error(err);
        reject(err);
      }
    })
  })
}

export default request;

用法:

参数:

TypeScript 复制代码
await request(
  url,      // 路径
  data,     // 数据
  method,   // 请求类型
  heeader,  // 请请求头(可选)
  timeout,  // 时间限制(可选)
)
相关推荐
棋宣16 分钟前
uni-app编译到微信小程序中,父传子props首次传递数据不接收的bug
微信小程序·uni-app·bug
Forget the Dream1 小时前
基于适配器模式的 Axios 封装实践
设计模式·typescript·axios·适配器模式
JiaWen技术圈1 小时前
HTTP/3 协议基础
网络·网络协议·http
烛衔溟17 小时前
TypeScript 接口继承与混合类型
linux·ubuntu·typescript
送鱼的老默17 小时前
学习笔记--入门typescript直接案例开搞
前端·typescript
Shingmc31 天前
【Linux】应用层协议HTTP
网络·网络协议·http
spmcor1 天前
TypeScript 中 null 与 undefined 的区别 —— 一篇彻底搞懂的指南
typescript
加号31 天前
【C#】 HTTP 请求通讯实现指南
开发语言·http·c#
CDN3601 天前
告别TCP队头阻塞!HTTP/3与QUIC协议在2026年的实战落地
网络协议·tcp/ip·http
Lsx_1 天前
H5 嵌入微信 / 支付宝 / 抖音小程序 WebView:调用原生能力完整方案
前端·微信小程序·webview