|
|
@@ -34,14 +34,15 @@ interface ResponseData<T = any> {
|
|
|
export const request = <T = any>(config: RequestConfig): Promise<T> => {
|
|
|
return new Promise((resolve, reject) => {
|
|
|
const { url, method = 'GET', data, header = {}, timeout = API_CONFIG.timeout } = config;
|
|
|
-
|
|
|
+
|
|
|
// 构建完整URL
|
|
|
- const fullUrl = url.startsWith('http') ? url : `${API_CONFIG.baseUrl}${url}`;
|
|
|
-
|
|
|
+ let fullUrl = url.startsWith('http') ? url : `${API_CONFIG.baseUrl}${url}`;
|
|
|
+
|
|
|
// 添加token到请求头
|
|
|
const token = getToken();
|
|
|
if (token) {
|
|
|
- header['access_token'] = token;
|
|
|
+ header['accessToken'] = token;
|
|
|
+
|
|
|
if (API_CONFIG.enableLog) {
|
|
|
console.log('[请求拦截] 添加token到请求头:', token.substring(0, 8) + '...');
|
|
|
}
|
|
|
@@ -50,17 +51,17 @@ export const request = <T = any>(config: RequestConfig): Promise<T> => {
|
|
|
console.warn('[请求拦截] 未找到token,请求将不携带token');
|
|
|
}
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
// 添加Content-Type
|
|
|
if (!header['Content-Type']) {
|
|
|
header['Content-Type'] = 'application/json';
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
// 打印请求日志
|
|
|
if (API_CONFIG.enableLog) {
|
|
|
console.log(`[请求] ${method} ${fullUrl}`, data);
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
// 发起请求
|
|
|
uni.request({
|
|
|
url: fullUrl,
|
|
|
@@ -73,9 +74,9 @@ export const request = <T = any>(config: RequestConfig): Promise<T> => {
|
|
|
if (API_CONFIG.enableLog) {
|
|
|
console.log(`[响应] ${method} ${fullUrl}`, res.data);
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
const responseData = res.data as ResponseData<T>;
|
|
|
-
|
|
|
+
|
|
|
// 处理HTTP状态码
|
|
|
if (res.statusCode !== 200) {
|
|
|
const errorMsg = `请求失败: HTTP ${res.statusCode}`;
|
|
|
@@ -86,7 +87,7 @@ export const request = <T = any>(config: RequestConfig): Promise<T> => {
|
|
|
reject(new Error(errorMsg));
|
|
|
return;
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
// 处理业务状态码
|
|
|
if (responseData.code === 200 || responseData.code === 0) {
|
|
|
// 成功
|
|
|
@@ -120,7 +121,7 @@ export const request = <T = any>(config: RequestConfig): Promise<T> => {
|
|
|
fail: (err: any) => {
|
|
|
// 网络错误
|
|
|
console.error(`[请求失败] ${method} ${fullUrl}`, err);
|
|
|
-
|
|
|
+
|
|
|
let errorMsg = '网络请求失败';
|
|
|
if (err.errMsg) {
|
|
|
if (err.errMsg.includes('timeout')) {
|
|
|
@@ -129,12 +130,12 @@ export const request = <T = any>(config: RequestConfig): Promise<T> => {
|
|
|
errorMsg = '网络连接失败,请检查网络';
|
|
|
}
|
|
|
}
|
|
|
-
|
|
|
+
|
|
|
uni.showToast({
|
|
|
title: errorMsg,
|
|
|
icon: 'none'
|
|
|
});
|
|
|
-
|
|
|
+
|
|
|
reject(new Error(errorMsg));
|
|
|
}
|
|
|
});
|