// utils/request.ts import { useUserStore } from '../store/user' // const baseURL = 'http://localhost:8888/api'; // 本地开发 // const baseURL = 'http://8.130.28.19:8060/api'; // 测试环境 const baseURL = 'https://eai-wx.seec.seecoder.cn/api';// 正式环境 // 不需要认证的接口路径列表 const noAuthUrls = [ '/login', // 登录接口 '/sms-code' // 发送验证码接口 // ... 其他不需要认证的接口,如注册、找回密码等 ]; export const request = (options: { url: string; // 这里的 url 是相对路径,例如 '/sms-code' method?: 'GET' | 'POST' | 'PUT' | 'DELETE'; data?: any; header?: Record; params?: Record; // 【新增】一个选项,可以显式覆盖是否需要认证,用于特殊情况 requireAuth?: boolean; }): Promise => { const userStore = useUserStore(); let requestUrl = baseURL + options.url; if (options.params) { const queryString = Object.keys(options.params) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(options.params![key])}`) .join('&'); requestUrl += `?${queryString}`; } // 【核心修改】判断当前请求是否需要认证 const token = userStore.token; // 默认需要认证,除非url在noAuthUrls中,或者options.requireAuth明确为false let shouldAttachAuthHeader = true; if (options.requireAuth === false || noAuthUrls.includes(options.url)) { shouldAttachAuthHeader = false; } // 如果明确要求认证,但没有token,则保持应该附带,但header会是空字符串 if (options.requireAuth === true) { shouldAttachAuthHeader = true; } return new Promise((resolve, reject) => { uni.request({ url: requestUrl, method: options.method || 'GET', data: options.data || {}, header: { 'Content-Type': 'application/json', // 【核心修改】根据 shouldAttachAuthHeader 判断是否添加 Authorization 头 ...(shouldAttachAuthHeader && token ? { 'Authorization': ` ${token}` } : {}), // ...(shouldAttachAuthHeader && token ? { 'Authorization': `Bearer ${token}` } : {}), ...options.header // 允许外部传入覆盖或添加其他header }, success: (res: UniApp.RequestSuccessCallbackResult) => { const responseData = res.data; // responseData 没有类型定义 if (responseData.code === 200) { resolve(responseData.data); } else { uni.showToast({ title: responseData.message || '操作失败', icon: 'none' }); reject(responseData); } }, fail: (err: UniApp.RequestFailCallbackResult) => { uni.showToast({ title: '网络错误,请稍后重试', icon: 'none' }); reject(err); } }); }); };