仿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`)
}
相关推荐
甜甜的资料库7 小时前
基于微信小程序的睡眠宝系统源码数据库文档
数据库·微信小程序·小程序
华子w9089258597 小时前
SpringBoot+uniapp 的 Champion 俱乐部微信小程序设计与实现,论文初版实现
spring boot·微信小程序·uni-app
恰薯条的屑海鸥8 小时前
关于我对各开发语言的看法与接下来的文章内容
开发语言·学习·微信小程序·网站开发·全栈开发
勿念4368 小时前
基于鸿蒙(HarmonyOS5)的打车小程序
华为·小程序·harmonyos
Stanford_110610 小时前
关于大数据的基础知识(二)——国内大数据产业链分布结构
大数据·开发语言·物联网·微信小程序·微信公众平台·twitter·微信开放平台
邹荣乐12 小时前
uni-app开发微信小程序的报错[渲染层错误]排查及解决
前端·微信小程序·uni-app
weixin_1772972206915 小时前
盲盒一番赏小程序:引领盲盒新潮流
小程序
chaosama1 天前
微信小程序带参分享、链接功能
微信小程序·小程序
胡西风_foxww1 天前
微信小程序动态组件加载的应用场景与实现方式
微信小程序·应用·加载·动态组件
ALLSectorSorft1 天前
上门服务小程序会员系统框架设计
小程序·apache