微信小程序的请求函数封装(ts版本,uniapp开发)
- 开源代码
- 2025-09-10 12:39:02

主要封装函数代码: 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 pleteRequest(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 ponent("qgy-loading", loading); app ponent("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) 步骤四:调用方法
request():正常发送请求
uploadFile():上传文件
completeRequest():可以配置完整url的路径发送请求
微信小程序的请求函数封装(ts版本,uniapp开发)由讯客互联开源代码栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“微信小程序的请求函数封装(ts版本,uniapp开发)”