仿axios,封装微信小程序的请求

由于小程序中的请求不是非常好用,没有axios好用,所以按照axios封装了一个简易的请求工具。

axiosWechat.js文件

javascript 复制代码
class AxiosWechat {
  constructor(config = {}) {
    // 设置基础配置
    this.config = {
      baseUrl: '',       // 基础路径
      headers: {},       // 请求头
      ...config,         // 合并用户传入的配置
    };
    // 初始化请求和响应拦截器数组
    this.requestInterceptors = [];
    this.responseInterceptors = [];
  }

  // 添加请求拦截器
  beforeRequest(fulfilled, rejected) {
    this.requestInterceptors.push({ fulfilled, rejected });
  }

  // 添加响应拦截器
  afterRequest(fulfilled, rejected) {
    this.responseInterceptors.push({ fulfilled, rejected });
  }

  // 通用请求方法
  request(config) {
    // 合并默认配置和请求配置
    config = { ...this.config, ...config };
    // 合并请求头
    config.headers = { ...this.config.headers, ...config.headers };

    let chain = Promise.resolve(config);

    // 执行请求拦截器
    this.requestInterceptors.forEach((interceptor) => {
      chain = chain.then(interceptor.fulfilled, interceptor.rejected);
    });

    // 发起请求
    chain = chain.then((finalConfig) => this._sendRequest(finalConfig));

    // 执行响应拦截器
    this.responseInterceptors.forEach((interceptor) => {
      chain = chain.then(interceptor.fulfilled, interceptor.rejected);
    });

    return chain;
  }

  // GET 请求方法
  get(url, params = {}, config = {}) {
    return this.request({
      url,
      method: 'GET',
      params,         // GET 请求使用 params
      ...config,
    });
  }

  // POST 请求方法
  post(url, data = {}, config = {}) {
    return this.request({
      url,
      method: 'POST',
      data,           // POST 请求使用 data
      ...config,
    });
  }

  // PUT 请求方法
  put(url, data = {}, config = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,           // PUT 请求使用 data
      ...config,
    });
  }

  // DELETE 请求方法
  delete(url, params = {}, config = {}) {
    return this.request({
      url,
      method: 'DELETE',
      params,         // DELETE 请求使用 params
      ...config,
    });
  }

  // 内部请求处理
  _sendRequest(config) {
    return new Promise((resolve, reject) => {
      const { baseUrl, url, method, data, params, headers } = config;

      let weixin = wx;
      if (typeof uni !== 'undefined') {
        weixin = uni;
      }

      // 发送请求
      weixin.request({
        url: baseUrl + url,
        method: method || 'GET',
        data: method === 'GET' || method === 'DELETE' ? params : data, // GET 和 DELETE 使用 params,其他使用 data
        header: headers,
        success: resolve,
        fail: reject,
      });
    });
  }
}

export default AxiosWechat;

初始化请求工具

index.js

javascript 复制代码
import axiosWechat from './axiosWechat.js'


const $http = new axiosWechat({
  baseUrl: 'https://xxxxxx',
  headers: { 'Content-Type': 'application/json;charset=UTF-8' },
});

// 请求拦截器
$http.beforeRequest((config) => {
    // 请求之前做需要做的
    return config;
  },
  (error) => {
    console.error('Request Interceptor Error:', error);
    return Promise.reject(error);
  }
);


// 响应拦截器
$http.afterRequest((response) => {
   	// 请求回来需要做的
	return response.data
  }
  },
  (error) => {
    console.error('Response Interceptor Error:', error);
    return Promise.reject(error);
  }
);


export default $http

文件中使用

javascript 复制代码
import axios from './index.js'
const base = "/api/ofa-admin"

export const login = (data) =>{
	// console.log(axios.post)
	return axios.post( `${base}/login`,  data, { headers: { ... } })
}

export const reqGetCodeImg = () =>{
	return axios.get( `${base}/open-api/captcha`)
}
相关推荐
游戏开发爱好者81 小时前
iOS 开发推送功能全流程详解 从 APNs 配置到上架发布的完整实践(含跨平台上传方案)
android·macos·ios·小程序·uni-app·cocoa·iphone
汤姆yu2 小时前
基于微信小程序的博物馆文创系统
微信小程序·小程序·博物馆
云起SAAS17 小时前
ai公司起名取名抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·ai公司起名取名
黑马源码库miui5208617 小时前
JAVA购物返利商品比价系统源码支持微信小程序
微信·微信小程序·小程序·1024程序员节
学会煎墙17 小时前
使用uniapp——实现微信小程序的拖拽排序(vue3+ts)
微信小程序·uni-app·vue·ts
淡淡蓝蓝18 小时前
uni-app小程序往飞书多维表格写入内容(包含图片)
小程序·uni-app·飞书
2501_9159214320 小时前
iOS混淆与IPA加固全流程(iOS混淆 IPA加固 Ipa Guard实战)
android·ios·小程序·https·uni-app·iphone·webview
游戏开发爱好者820 小时前
iOS 26 App 开发阶段性能优化 从多工具协作到数据驱动的实战体系
android·ios·小程序·uni-app·iphone·webview·1024程序员节
2501_9151063220 小时前
深入剖析 iOS 26 系统流畅度,多工具协同监控与性能优化实践
android·ios·性能优化·小程序·uni-app·cocoa·iphone
游戏开发爱好者81 天前
iOS 26 App 查看电池寿命技巧,多工具组合实践指南
android·macos·ios·小程序·uni-app·cocoa·iphone