vue3基于uni-app 封装小程序request请求
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue
免费下载资源
·
const BASE_URL = 'https://47.122.26.142'; // 替换为你的 API 基础 URL
const token = uni.getStorageSync('token');
const request = (url: string, method: any, data = {}, headers = {}) => {
return new Promise((resolve, reject) => {
uni.request({
url: `${BASE_URL}${url}`,
method,
data,
//请求头参数自定义
header: {...headers, 'X-Token' : String(token)},
timeout: 10000,
success: (response) => {
if (response.statusCode === 200) {
resolve(response.data);
} else {
handleError(response);
reject(response);
}
},
fail: (error) => {
uni.showToast({ title: '网络错误', icon: 'none' });
reject(error);
},
});
});
};
const handleError = (response: UniApp.RequestSuccessCallbackResult) => {
switch (response.statusCode) {
case 401:
uni.showToast({ title: '请先登录', icon: 'none' });
// 跳转到登录页的逻辑
break;
case 404:
uni.showToast({ title: '资源未找到', icon: 'none' });
break;
default:
uni.showToast({ title: '请求错误', icon: 'none' });
break;
}
};
const http = {
get(url: string, params = {}, headers = {}) {
console.log('请求参数', headers);
return request(url, 'GET', params, headers);
},
post(url: any, data = {}, headers = {}) {
return request(url, 'POST', data, headers);
},
put(url: any, data = {}, headers = {}) {
return request(url, 'PUT', data, headers);
},
delete(url: any, data = {}, headers = {}) {
return request(url, 'DELETE', data, headers);
},
};
export default http;
使用新建interface.ts
import http from '@/utils/request'
const application = "application/json;charset=UTF-8";
const formData = "multipart/form-data";
const plain = "application/json, text/plain, */*";
const {post, get, put} = http
// Content-Type 根据实际接口选择
export const apiGetMyNotice = (data: any) => {
return get(`/api/workflowProcess/getMyNotice`, data, {"Content-Type":application});
};
在页面使用同常规一样
<script setup lang="ts">
import { apiGetMyNotice } from "@/apis/interface";
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { computed, onMounted, reactive } from "vue";
onMounted(() => {
onApiGetMyNotice();
});
const onApiGetMyNotice = async () => {
try {
const response = await apiGetMyNotice({});
console.log(response);
} catch (error) {
console.error(error);
}
};
</script>
GitHub 加速计划 / vu / vue
80
16
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:4 个月前 )
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 6 个月前
e428d891
Updated Browser Compatibility reference. The previous currently returns HTTP 404. 6 个月前
更多推荐
已为社区贡献3条内容
所有评论(0)