You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
2.6 KiB

4 months ago
// utils/request.js
/**
* 封装请求函数
* @param {Object} options - 请求选项
* @param {string} options.url - 请求URL
* @param {string} options.method - 请求方法: GET, POST, PUT, DELETE
* @param {Object} options.data - 请求参数
* @param {Object} options.header - 请求头
* @returns {Promise} - 返回Promise对象
*/
3 months ago
4 months ago
export const request = (options = {}) => {
2 months ago
const DOMAIN = 'https://m.dayunyuanjian.com';
3 months ago
return new Promise((resolve, reject) => {
options.url = options.url.startsWith('/') ? `${DOMAIN}${options.url}` : options.url;
// 默认配置
const defaultOptions = {
url: '',
method: 'GET',
data: {},
header: {
'content-type': 'application/json'
},
timeout: 10000 // 10秒超时
};
// 合并配置
const mergedOptions = {
...defaultOptions,
...options
};
// 处理URL
if (!mergedOptions.url) {
reject(new Error('URL不能为空'));
return;
}
// 调用uni.request
uni.request({
url: mergedOptions.url,
method: mergedOptions.method,
data: mergedOptions.data,
header: mergedOptions.header,
timeout: mergedOptions.timeout,
success: (res) => {
// 请求成功
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(res.data);
} else {
// 服务器返回错误
reject({
statusCode: res.statusCode,
errMsg: `请求失败,状态码: ${res.statusCode}`,
data: res.data
});
}
},
fail: (err) => {
// 请求失败
reject(err);
}
});
});
4 months ago
};
/**
* GET请求快捷方法
* @param {string} url - 请求URL
* @param {Object} data - 请求参数
* @param {Object} options - 其他选项
*/
export const get = (url, data = {}, options = {}) => {
3 months ago
return request({
url,
method: 'GET',
data,
...options
});
4 months ago
};
/**
* POST请求快捷方法
* @param {string} url - 请求URL
* @param {Object} data - 请求参数
* @param {Object} options - 其他选项
*/
export const post = (url, data = {}, options = {}) => {
3 months ago
return request({
url,
method: 'POST',
data,
...options
});
4 months ago
};
/**
* 上传文件快捷方法
* @param {string} url - 上传URL
* @param {string} filePath - 文件路径
* @param {string} name - 文件对应的key
* @param {Object} formData - 附加的表单数据
*/
export const uploadFile = (url, filePath, name = 'file', formData = {}) => {
3 months ago
return new Promise((resolve, reject) => {
uni.uploadFile({
url,
filePath,
name,
formData,
success: (res) => {
try {
// 尝试解析JSON
const data = JSON.parse(res.data);
resolve(data);
} catch (e) {
resolve(res.data);
}
},
fail: reject
});
});
};