主要封装函数代码:
- 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的路径发送哀求
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |