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>