原生微信小程序封装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,  // 时间限制(可选)
)
相关推荐
风月歌33 分钟前
基于微信小程序的学习资料销售平台源代码(源码+文档+数据库)
java·数据库·mysql·微信小程序·小程序·毕业设计·源码
多仔ヾ1 小时前
微信小程序开发实战之 05-微信小程序常用 API(下)
微信小程序
教练、我想打篮球1 小时前
120 同样的 url, header, 参数, 使用 OkHttp 能够成功获取数据, 使用 RestTemplate 报错
http·okhttp·resttemplate·accept
半兽先生1 小时前
微信小程序与web-view页面双向通信
前端·微信小程序·小程序
小明记账簿1 小时前
微信小程序中Crypto.js加密解密
微信小程序·小程序·加密·解密
zfj3211 小时前
websocket为什么需要在tcp连接成功后先发送一个标准的http请求,然后在当前tcp连接上升级协议成websocket
websocket·tcp/ip·http
qq_12498707531 小时前
基于springboot的幼儿园家校联动小程序的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·spring·微信小程序·小程序
多仔ヾ1 小时前
微信小程序开发实战之 06-微信小程序开发进阶
微信小程序
杀手不太冷!1 小时前
Jenkins的安装与使用;git clone url的时候,url为http和ssh时候的区别
git·http·jenkins
前端老白2 小时前
webview在微信小程序中,安卓加载失败,IOS正常加载
android·ios·微信小程序·webview