294 lines
7.0 KiB
JavaScript
294 lines
7.0 KiB
JavaScript
import dayjs from 'dayjs';
|
|
import { PLATFORM,BASE_URL } from '@/utils/config.js'
|
|
import {initLogin} from '@/utils/login.js'
|
|
|
|
// 平台适配配置
|
|
const PLATFORM_CONFIG = {
|
|
'mp-weixin': {
|
|
storageKey: 'wx_token',
|
|
authHeader: 'Authorization'
|
|
},
|
|
'mp-kuaishou': {
|
|
storageKey: 'ks_token',
|
|
authHeader: 'Authorization'
|
|
}
|
|
};
|
|
|
|
// 获取当前平台配置
|
|
function getPlatformConfig() {
|
|
const defaultConfig = {
|
|
storageKey: 'token',
|
|
authHeader: 'Authorizationn',
|
|
baseURL: BASE_URL
|
|
};
|
|
|
|
// 合并平台配置
|
|
return {
|
|
...defaultConfig,
|
|
...(PLATFORM_CONFIG[PLATFORM] || {})
|
|
};
|
|
}
|
|
|
|
// 请求拦截器
|
|
const requestInterceptor = (config, encrypted) => {
|
|
// 加密处理逻辑
|
|
if (encrypted) {
|
|
if (config.data) {
|
|
try {
|
|
const data = JSON.stringify(config.data);
|
|
const key = dayjs().format('YYYYMMDDHHmmss');
|
|
config.data = encode(data, key); // 确保encode函数已定义
|
|
config.header = {
|
|
'x-encode-key': key,
|
|
'Content-Type': 'text/plain; charset=utf-8',
|
|
};
|
|
} catch (error) {
|
|
console.error('请求加密失败:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 获取平台配置
|
|
const platformConfig = getPlatformConfig();
|
|
|
|
// 添加token
|
|
try {
|
|
console.log("getStorageSync:",uni.getStorageSync(platformConfig.storageKey),platformConfig.storageKey)
|
|
const token = uni.getStorageSync(platformConfig.storageKey);
|
|
if (token) {
|
|
config.header = config.header || {};
|
|
config.header[platformConfig.authHeader] = `Bearer ${token}`;
|
|
config.header[platformConfig.authHeader] = token;
|
|
|
|
}
|
|
} catch (error) {
|
|
console.warn('获取存储token失败:', error);
|
|
}
|
|
|
|
// 添加通用头
|
|
if (!encrypted) {
|
|
config.header = {
|
|
...(config.header || {}),
|
|
'Content-Type': 'application/json',
|
|
'X-Platform': PLATFORM
|
|
};
|
|
}
|
|
|
|
// 处理URL
|
|
if (!config.url.startsWith('http')) {
|
|
config.url = `${platformConfig.baseURL}${config.url}`;
|
|
}
|
|
|
|
|
|
console.log('[Request]', config.method, config.url,config);
|
|
return config;
|
|
};
|
|
|
|
// 响应拦截器
|
|
const responseInterceptor = (response) => {
|
|
console.log('[Response]', response.statusCode, response);
|
|
|
|
// 响应成功处理
|
|
if (response.statusCode >= 200 && response.statusCode < 300) {
|
|
// 添加业务状态码处理逻辑
|
|
if (response.data.code === 200) {
|
|
if (response.data.code === 201 && response.data.data && response.data.timestamp) {
|
|
try {
|
|
const result = decode(response.data.data, response.data.timestamp); // 确保decode函数已定义
|
|
response.data = JSON.parse(result);
|
|
return response.data;
|
|
} catch (error) {
|
|
console.error('响应解密失败:', error);
|
|
throw new Error('响应解密失败');
|
|
}
|
|
}
|
|
return response.data;
|
|
} else {
|
|
// 业务错误处理
|
|
return Promise.reject({
|
|
code: response.data.code,
|
|
message: response.data.msg || '业务逻辑错误'
|
|
});
|
|
}
|
|
}
|
|
|
|
// HTTP错误处理
|
|
const errorMap = {
|
|
400: '请求参数错误',
|
|
401: '登录已过期,请重新登录',
|
|
403: '拒绝访问',
|
|
404: '请求地址错误',
|
|
500: '服务器内部错误'
|
|
};
|
|
|
|
const errorMessage = errorMap[response.statusCode] || `服务器错误: ${response.statusCode}`;
|
|
|
|
// 401特殊处理
|
|
if (response.statusCode === 401) {
|
|
try {
|
|
const platformConfig = getPlatformConfig();
|
|
uni.removeStorageSync(platformConfig.storageKey);
|
|
uni.showToast({
|
|
title: '登录已过期,请重新登录',
|
|
icon: 'none',
|
|
complete: () => {
|
|
setTimeout(() => {
|
|
initLogin()
|
|
}, 1500);
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error('401处理失败:', error);
|
|
}
|
|
}
|
|
|
|
return Promise.reject({
|
|
code: response.statusCode,
|
|
message: errorMessage
|
|
});
|
|
};
|
|
|
|
// 错误处理
|
|
const errorHandler = (error) => {
|
|
console.error('[Error]', error);
|
|
|
|
// 统一错误提示
|
|
let errorMessage = error.message || '未知错误';
|
|
|
|
// 网络错误特殊处理
|
|
if (error.errMsg && error.errMsg.indexOf('request:fail') !== -1) {
|
|
errorMessage = '网络连接失败,请检查网络设置';
|
|
}
|
|
|
|
// 不在401跳转时显示错误消息
|
|
if (error.code !== 401) {
|
|
uni.showToast({
|
|
title: errorMessage,
|
|
icon: 'none',
|
|
duration: 3000
|
|
});
|
|
}
|
|
|
|
return Promise.reject(error);
|
|
};
|
|
|
|
// 创建请求实例
|
|
const createRequest = () => {
|
|
return async (options) => {
|
|
// 初始化配置
|
|
const config = {
|
|
url: options.url,
|
|
method: options.method || 'GET',
|
|
header: options.header || {},
|
|
data: options.data || {},
|
|
timeout: options.timeout || 15000,
|
|
encrypted: options.encrypted
|
|
};
|
|
|
|
try {
|
|
// 请求拦截处理
|
|
const processedConfig = requestInterceptor(config, options.encrypted);
|
|
|
|
console.log("createRequest after requestInterceptor:",processedConfig)
|
|
// 发起请求
|
|
const response = await new Promise((resolve, reject) => {
|
|
uni.request({
|
|
...processedConfig,
|
|
success: resolve,
|
|
fail: reject
|
|
});
|
|
});
|
|
|
|
// 响应拦截处理
|
|
return responseInterceptor(response);
|
|
} catch (error) {
|
|
return errorHandler(error);
|
|
}
|
|
};
|
|
};
|
|
|
|
// 常用请求方法
|
|
const http = {
|
|
get: (url, params, config = {}) => {
|
|
return createRequest()({
|
|
url,
|
|
method: 'GET',
|
|
data: params,
|
|
...config
|
|
});
|
|
},
|
|
|
|
post: (url, data, config = {}) => {
|
|
return createRequest()({
|
|
url,
|
|
method: 'POST',
|
|
data,
|
|
...config
|
|
});
|
|
},
|
|
|
|
put: (url, data, config = {}) => {
|
|
return createRequest()({
|
|
url,
|
|
method: 'PUT',
|
|
data,
|
|
...config
|
|
});
|
|
},
|
|
|
|
delete: (url, config = {}) => {
|
|
return createRequest()({
|
|
url,
|
|
method: 'DELETE',
|
|
...config
|
|
});
|
|
},
|
|
|
|
// 下载文件方法
|
|
download: (url, config = {}) => {
|
|
return new Promise((resolve, reject) => {
|
|
// 获取平台配置
|
|
const platformConfig = getPlatformConfig();
|
|
|
|
// 获取token
|
|
let token;
|
|
try {
|
|
token = uni.getStorageSync(platformConfig.storageKey);
|
|
} catch (error) {
|
|
console.warn('获取存储token失败:', error);
|
|
}
|
|
|
|
// 设置请求头
|
|
const header = {};
|
|
if (token) {
|
|
header[platformConfig.authHeader] = `Bearer ${token}`;
|
|
}
|
|
|
|
// 处理URL
|
|
let reqUrl = url;
|
|
if (!reqUrl.startsWith('http')) {
|
|
reqUrl = `${platformConfig.baseURL}${url}`;
|
|
}
|
|
|
|
// 发起下载请求
|
|
uni.downloadFile({
|
|
url: reqUrl,
|
|
header: header,
|
|
success: (res) => {
|
|
if (res.statusCode === 200) {
|
|
resolve(res);
|
|
} else {
|
|
reject(new Error(`下载失败,状态码: ${res.statusCode}`));
|
|
}
|
|
},
|
|
fail: reject
|
|
});
|
|
});
|
|
}
|
|
};
|
|
|
|
// 全局挂载
|
|
uni.$http = http;
|
|
|
|
export default http; |