微信小程序的请求函数封装(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)
步骤四:调用方法
-
request():正常发送请求
-
uploadFile():上传文件
-
completeRequest():可以配置完整url的路径发送请求