Files
template-MP/api/request.js
2025-11-05 16:20:06 +08:00

163 lines
4.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Request from '@/lib/luch-request/index.js'
import tool from '@/common/utils/tool.js'
import EnvConfig from '@/common/utils/env.js'
const baseUrl = EnvConfig.BASE_URL
const http = new Request()
// 缓存存储
const cache = new Map()
// 缓存过期时间毫秒默认5分钟
const CACHE_EXPIRATION = 5 * 60 * 1000
// 缓存工具方法
const cacheUtils = {
// 生成缓存key
generateKey(config) {
return `${config.method}:${config.url}:${JSON.stringify(config.data || {})}:${JSON.stringify(config.params || {})}`
},
// 获取缓存
get(key) {
const cached = cache.get(key)
if (!cached) return null
// 检查是否过期
if (Date.now() - cached.timestamp > CACHE_EXPIRATION) {
cache.delete(key)
return null
}
return cached.data
},
// 设置缓存
set(key, data) {
cache.set(key, {
data,
timestamp: Date.now(),
})
},
// 清除缓存
clear() {
cache.clear()
},
// 清除指定缓存
delete(key) {
cache.delete(key)
},
}
/* 设置全局配置 */
http.setConfig(config => {
config.header = { ...config.header }
config.sslVerify = false
config.baseURL = baseUrl
return config
})
http.interceptors.request.use(
async config => {
config.header = { ...config.header }
// 自动添加token
const token = uni.getStorageSync('token')
if (token) {
config.header.Authorization = `Bearer ${token}`
}
// 添加通用请求头
config.header['Content-Type'] = 'application/json'
// 检查缓存
if (config.method === 'GET' && config.cache !== false) {
const cacheKey = cacheUtils.generateKey(config)
const cachedData = cacheUtils.get(cacheKey)
if (cachedData) {
// 如果有缓存,直接返回缓存数据
return Promise.resolve({
data: cachedData,
statusCode: 200,
})
}
}
return config
},
config => {
return Promise.reject(config)
}
)
http.interceptors.response.use(
response => {
// 网络错误处理
if (response.statusCode >= 500) {
console.error('服务器错误:', response)
tool.alert('服务器错误,请稍后重试')
return Promise.reject(response)
}
if (response.statusCode === 404) {
console.error('接口不存在:', response)
tool.alert('接口不存在')
return Promise.reject(response)
}
if (response.statusCode === 403) {
console.error('无权限访问:', response)
tool.alert('无权限访问')
return Promise.reject(response)
}
// 未授权处理
if (response.statusCode === 401 || response.data?.code === 401) {
console.error('未授权或登录过期:', response)
tool.alert('登录已过期,请重新登录')
// 清除本地token
uni.removeStorageSync('token')
// 跳转到登录页
setTimeout(() => {
uni.reLaunch({ url: '/pages/login/login' }) // 根据实际登录页路径调整
}, 1500)
return Promise.reject(response)
}
// 业务错误处理
if (response.data && response.data.code !== undefined && response.data.code !== 200) {
const message = response.data.message || response.data.msg || '业务错误'
console.error('业务错误:', message)
tool.alert(message)
return Promise.reject(response)
}
// 成功响应
if (response.statusCode === 200) {
// 缓存GET请求的响应数据
if (response.config && response.config.method === 'GET' && response.config.cache !== false) {
const cacheKey = cacheUtils.generateKey(response.config)
cacheUtils.set(cacheKey, response.data)
}
return Promise.resolve(response)
} else {
return Promise.reject(response)
}
},
error => {
console.error('请求失败:', error)
if (error.errMsg) {
// 网络错误
tool.alert('网络连接失败,请检查网络')
} else {
tool.alert('请求失败,请稍后重试')
}
return Promise.reject(error)
}
)
// 添加缓存功能到http实例
http.cache = cacheUtils
// 添加重试方法
http.retry = async function (config, retries = 3, delay = 1000) {
return new Promise((resolve, reject) => {
const attempt = async retryCount => {
try {
const response = await this.request(config)
resolve(response)
} catch (error) {
if (retryCount <= 0) {
reject(error)
} else {
// 延迟后重试
setTimeout(() => {
attempt(retryCount - 1)
}, delay)
}
}
}
attempt(retries)
})
}
export default http