import { useUserStore } from "../stores/modules/userInfo" // const baseURL = "https://hwjb.homilychart.com/testApi" const baseURL = "http://192.168.40.8:9000" const httpInterceptor = { // 拦截前触发 invoke(options) { // 打印当前 baseURL 便于定位来源 console.log('HTTP(baseURL)=', baseURL) // 若出现旧代码将 url 设为 http://localhost:8888,强制改为真实域名 if (options.url.startsWith('http://localhost:8888')) { options.url = baseURL.replace(/\/$/, '') + options.url.replace('http://localhost:8888', '') } else if (options.url.startsWith('https://localhost:8888')) { options.url = baseURL.replace(/\/$/, '') + options.url.replace('https://localhost:8888', '') } // 仅当明确配置了 baseURL 时才拼接前缀(去掉 baseURL 尾部的斜杠,避免双斜杠) if (baseURL && !options.url.startsWith('http')) { options.url = baseURL.replace(/\/$/, '') + options.url } // 打印最终请求地址 console.log('HTTP(finalUrl)=', options.url) // 2.请求超时,默认60s options.timeout = 60000 console.log(options) //3 添加小程序端请求头 const sys = uni.getSystemInfoSync(); // 为对齐后端文档示例,client 固定为 ios(如需按平台设置再改回) const client = 'ios'; options.header = { ...options.header, 'source-client': 'miniapp', // 标准头与文档头同时设置,确保兼容 'content-type': 'application/json', // 'contentType': 'application/json', 'version': '1', 'client': client, 'deviceId':'1' } //4 添加token,优先用store,没有则回退到body中的token,保持与Apifox一致 const memberStore = useUserStore() // const token = memberStore.userInfo?.token || options.data?.token options.header.token = '9cd87893b9282b6a7a6cc9b780c905db' const token = '9cd87893b9282b6a7a6cc9b780c905db' if (token) { options.header.token = token } // 避免误用 Authorization 头,后端要求的是 token 头 // if (options.header.Authorization) delete options.header.Authorization return options } } // 添加拦截器 uni.addInterceptor('request', httpInterceptor) uni.addInterceptor('uploadFile', httpInterceptor) // 添加请求函数 export const http = (options) => { return new Promise((resolve, reject) => { uni.request({ ...options, // 1.请求成功 success: (result) => { if (result.statusCode >= 200 && result.statusCode < 300) { resolve(result.data) } else if (result.statusCode === 401) { // 清除登录信息 const memberStore = useUserStore() memberStore.clearUserInfo() // 提示用户重新登录 uni.navigateTo({ url: '/pages/login/login' }) reject(result) } else { uni.showToast({ title: (result.data).msg || '请求失败', icon: 'none' }) reject(result) } }, // 2.请求失败 fail: (err) => { reject(err) uni.showToast({ title: '网络错误', icon: 'none' }) } }) }) }