// HTTP模块配置文件 /** * 环境配置 */ const ENV_CONFIG = { // 开发环境 development: { baseURL: 'http://localhost:8888', timeout: 30000 }, // 测试环境 testing: { baseURL: 'https://test-api.pet-ai.com', timeout: 30000 }, // 生产环境 production: { baseURL: 'https://api.pet-ai.com', timeout: 60000 } } /** * 当前环境 (可根据实际情况动态设置) */ let CURRENT_ENV = 'development' // development | testing | production /** * HTTP基础配置 */ export const HTTP_CONFIG = { // 当前环境配置 ...ENV_CONFIG[CURRENT_ENV], // 登录页面路径 loginPage: '/pages/login/login', // 存储键名配置 storageKeys: { token: 'token', refreshToken: 'refreshToken', userInfo: 'userInfo' }, // 请求重试配置 retry: { times: 2, // 重试次数 delay: 1000, // 重试延迟(毫秒) statusCodes: [500, 502, 503, 504] // 需要重试的状态码 } } /** * 不需要鉴权的接口列表 * 注意:只需要配置不需要token的接口,其他接口默认都需要鉴权 */ export const NO_AUTH_APIS = [ // 用户认证相关 '/wechat/user/mini/login', // 微信小程序登录 ] /** * 需要鉴权的接口列表(明确需要登录的接口) * 这些接口在调用时如果未登录会自动跳转到登录页面 */ export const AUTH_REQUIRED_APIS = [ // 微信小程序用户相关接口 '/user/wechat/mini/userinfo', // 获取用户信息 '/user/wechat/mini/phone-update', // 更新手机号 '/user/wechat/mini/check-unionid', // 检查UnionID ] /** * 检查接口是否需要鉴权 * @param {String} url 接口URL * @returns {Boolean} 是否需要鉴权 */ export function checkApiAuth(url) { // 移除查询参数,只保留路径 const path = url.split('?')[0] // 检查是否在不需要鉴权的列表中 for (const noAuthApi of NO_AUTH_APIS) { // 支持通配符匹配 if (noAuthApi.includes('*')) { const regex = new RegExp('^' + noAuthApi.replace(/\*/g, '.*') + '$') if (regex.test(path)) { return false } } else if (path === noAuthApi || path.startsWith(noAuthApi + '/')) { return false } } // 默认需要鉴权 return true } /** * 检查接口是否需要强制登录 * @param {String} url 接口URL * @returns {Boolean} 是否需要强制登录 */ export function checkAuthRequiredApi(url) { // 移除查询参数,只保留路径 const path = url.split('?')[0] // 检查是否在需要强制登录的列表中 for (const authApi of AUTH_REQUIRED_APIS) { // 支持通配符匹配 if (authApi.includes('*')) { const regex = new RegExp('^' + authApi.replace(/\*/g, '.*') + '$') if (regex.test(path)) { return true } } else if (path === authApi || path.startsWith(authApi + '/')) { return true } } return false } /** * 添加不需要鉴权的接口 * @param {String|Array} apis 接口路径或接口路径数组 */ export function addNoAuthApis(apis) { if (Array.isArray(apis)) { NO_AUTH_APIS.push(...apis) } else { NO_AUTH_APIS.push(apis) } } /** * 设置当前环境 * @param {String} env 环境名称 (development | testing | production) */ export function setEnvironment(env) { if (ENV_CONFIG[env]) { CURRENT_ENV = env // 更新HTTP配置 Object.assign(HTTP_CONFIG, ENV_CONFIG[env]) console.log(`HTTP环境已切换到: ${env}`) console.log(`当前baseURL: ${HTTP_CONFIG.baseURL}`) } else { console.error(`无效的环境名称: ${env}`) } }