You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
import { useUserStore } from "../stores/modules/userInfo"import { useDeviceStore } from "../stores/modules/deviceInfo"
const baseURL = "https://hwjb.homilychart.com/testApi"
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 deviceInfo =useDeviceStore()
options.header = { ...options.header, // 标准头与文档头同时设置,确保兼容
'content-type': 'application/json', 'contentType': 'application/json', 'version': uni.getSystemInfoSync().appVersion, 'client': uni.getSystemInfoSync().platform == 'ios' ? 'ios' : 'android', 'deviceId': deviceInfo.deviceInfo.deviceId } //4 添加token,优先用store,没有则回退到body中的token,保持与Apifox一致
const memberStore = useUserStore() const token = memberStore.userInfo?.token || options.data?.token // const token = '2d0b5654409646713cdd40ec0d0bb56c'
// const token = '1b3a58424c5324e40d4bf4d085e18047'
if (token) { options.header.token = token } console.log("最终请求参数:",options) // 避免误用 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) { if (result.data.code === 401) { uni.showToast({ title: '请先登录', icon: 'none' }) } 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' }) } }) })}
|