当前位置: 首页 > news >正文

微信小程序的请求函数封装(ts版本,uniapp开发)

 主要封装函数代码:

interface HttpOptions {
    url: string;
    method?: string;
    headers?: { [key: string]: string };
    data?: any;
}

class Http {

    private timeout: number;
    private baseUrl: string;

    public constructor() { 
        this.timeout = 60 * 1000;
        this.baseUrl = 'http://localhost:8088/';
    }

    //全局设置地址
    public setBaseUrl(url: string) {
        this.baseUrl = url;
    }

    //全局设置超时时间
    public setTimeout(timeout: number) {
        this.timeout = timeout;
    }

    //小程序发送请求
    public async request(options: HttpOptions) {
        options.url = this.baseUrl + options.url;
        return this.completeRequest(options);
    }

    //小程序上传文件
    public async uploadFile(options: HttpOptions) {
        const { url, headers = { 'Content-Type': 'multipart/form-data' }, data } = options;
        return new Promise((resolve, reject) => {
            uni.uploadFile({
                url: this.baseUrl + url,
                header: headers,
                files: data,
                success: (res) => {
                    resolve(res.data)
                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }

    //完整路经的请求
    public async completeRequest(options: HttpOptions) {
        const { url, method = 'GET', headers = { 'Content-Type': 'application/json' }, data } = options;
        return new Promise((resolve, reject) => {
            uni.request({
                url: url,
                timeout: this.timeout,
                method: method as 'GET' | 'POST',
                header: headers,
                data: data,
                success: (res) => {
                    resolve(res.data)
                },
                fail: (err) => {
                    reject(err)
                }
            })
        })
    }
}

//导出实例和类
export default new Http();

export { Http };

使用方法

步骤一:在main文件中全局依赖注入
import { createSSRApp } from "vue";
import App from "./App.vue";
//导入加载页面组件
import loading from "./component/loading.vue";
import drawer from "./component/drawer.vue";
import wxShare from "./util/wxShare";
//导入HTTP请求
import http from "./util/http";
export function createApp() {
  const app = createSSRApp(App);
  app.component("qgy-loading", loading);
  app.component("qgy-drawer", drawer);
  app.mixin(wxShare);
  //全局挂载http
  app.provide("$http", http);
  return {
    app,
  };
}
步骤二:在组件中导入
import { inject, onMounted } from 'vue'
import { Http } from '@/util/http';

const http:Http|undefined = inject('$http');
步骤三:设置全局配置
//设置全局配置
http.setBaseUrl("http://localhost:8088/")
http.setTimeout(60 * 1000)
步骤四:调用方法
  1. request():正常发送请求

  2. uploadFile():上传文件

  3. completeRequest():可以配置完整url的路径发送请求

http://www.dtcms.com/a/20081.html

相关文章:

  • 【电路笔记】-双向计数器
  • 【VUE】前端工程化与前端工程化与webpack
  • css简介
  • 哈希表(C语言版)
  • 【stm32】定时器输出PWM波形(hal库)
  • Qt的QPushButton样式设置
  • 半遮挡检测算法 Detecting Binocular Half-Occlusions
  • 19.4.2 -19.4.4 新增、修改、删除数据
  • SpringBoot服务器的采购上,服务器的数量和性能配置如何取舍【无标题】
  • Day2 25/2/15 SAT
  • electron打包基本教程
  • Flutter中 List列表中移除特定元素
  • QEMU 搭建arm linux开发环境
  • 纪念日倒数日项目的实现-【纪念时刻-时光集】
  • Debezium系列之:时区转换器,时间戳字段转换到指定时区
  • SpringCloud Alibaba
  • tensorflow环境中已安装库
  • 【Java集合二】HashMap 详解
  • 【NLP 24、模型训练方式】
  • Leetcode 算法题 88. 合并两个有序数组
  • 【含文档+源码】基于Web的在线课堂测试课程考评系统的开发与实现
  • GPQA (Graduate-Level Google-Proof QA Benchmark) 数据集
  • 图像处理篇---基本OpenMV图像处理
  • HackerRank C++面试,中等难度题目 - Attribute Parser
  • Bandana论文阅读
  • 复杂电磁环境下无人机自主导航增强技术研究报告——地磁匹配与多源数据融合方法,附matlab代码
  • 基于多元高斯分布的异常检测技术原理与实现
  • lean4安装
  • 论文阅读2——S波段宽波束圆极化天线设计
  • 【ISO 14229-1:2023 UDS诊断(会话控制0x10服务)测试用例CAPL代码全解析⑤】