| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- // 从环境变量中获取基础地址,如果没有设置则使用默认值
- const BASE_URL = import.meta.env.VITE_APP_BASE_URL || 'https://default-api-url.com';
- // 默认配置
- const defaultConfig = {
- timeout: 5000, // 默认超时时间为 5000 毫秒
- baseURL: BASE_URL // 基础 URL
- };
- // 辅助函数:将对象转换为查询字符串
- function objectToQueryString(obj) {
- return Object.keys(obj)
- .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
- .join('&');
- }
- // 封装请求函数
- function request(options) {
- const config = {
- ...defaultConfig,
- ...options
- };
- // 拼接完整的请求 URL
- config.url = config.baseURL + config.url;
- return new Promise((resolve, reject) => {
- uni.request({
- ...config,
- success: (res) => {
- resolve(res.data);
- },
- fail: (err) => {
- reject(err);
- }
- });
- });
- }
- // 封装 GET 请求
- export const clientGet = async (url, data = {}) => {
- try {
- const response = await request({
- url,
- method: 'GET',
- data
- });
- return response;
- } catch (error) {
- throw error;
- }
- };
- // 封装 POST 请求
- export const clientPost = async (url, data = {}) => {
- try {
- const response = await request({
- url,
- method: 'POST',
- data
- });
- return response;
- } catch (error) {
- throw error;
- }
- };
- // 封装 PUT 请求
- export const clientPut = async (url, data = {}) => {
- try {
- const response = await request({
- url,
- method: 'PUT',
- data
- });
- return response;
- } catch (error) {
- throw error;
- }
- };
- // 封装 DELETE 请求
- export const clientDelete = async (url, data = {}) => {
- try {
- const response = await request({
- url,
- method: 'DELETE',
- data
- });
- return response;
- } catch (error) {
- throw error;
- }
- };
- // 封装带查询参数的 POST 请求
- export const clientPostWithQueryParams = async (url, queryParams = {}, data = {}) => {
- try {
- const queryString = objectToQueryString(queryParams);
- const fullUrl = url + (queryString ? `?${queryString}` : '');
- const response = await request({
- url: fullUrl,
- method: 'POST',
- data
- });
- return response;
- } catch (error) {
- throw error;
- }
- };
|