import store from '@/store' import config from '@/config' import { getToken } from '@/utils/auth' import errorCode from '@/utils/errorCode' import { toast, showConfirm, tansParams } from '@/utils/common' import { encrypt, decrypt } from '@/utils/crypto.js' let timeout = 10000 const baseUrl = config.baseUrl const request = config => { // 是否需要设置 token const isToken = (config.headers || {}).isToken === false config.header = config.header || {} if (getToken() && !isToken) { config.header['token'] = getToken() config.header['Authorization'] = 'Bearer ' + getToken() } const hospId = uni.getStorageSync('hospId') if (hospId) { config.header['hospId'] = hospId } // get 请求映射 params 参数 if (config.params) { let url = config.url + '?' + tansParams(config.params) url = url.slice(0, -1) config.url = url } // 检查是否为登录请求 const isLoginRequest = config.url.includes('/login') // 根据你的登录接口路径调整条件 let data = config.data if (!isLoginRequest) { // 非登录请求,加密数据 data = encrypt(JSON.stringify(config.data)) } else { // 登录请求,保持数据原样(或根据需要序列化) data = JSON.stringify(config.data) } return new Promise((resolve, reject) => { uni.request({ method: config.method || 'get', timeout: config.timeout || timeout, url: config.baseUrl || baseUrl + config.url, data: data, header: config.header, responseType: config.responseType || 'text', dataType: config.responseType === 'arraybuffer' ? undefined : 'json' }).then(response => { console.log('原始响应:', response, 12222222) let [error, res] = response if (error) { toast('后端接口连接异常') reject('后端接口连接异常') return } let resdate; try { if (isLoginRequest) { // 登录请求,检查 res.data 类型 resdate = typeof res.data === 'string' ? JSON.parse(res.data) : res.data } else { // 非登录请求,解密数据 let resdates = decrypt(res.data) resdate = JSON.parse(resdates) } console.log('解析后的响应:', resdate, 22222) } catch (e) { console.error('解密或解析错误:', e) toast('响应数据处理失败') reject('响应数据处理失败') return } // 如果是 arraybuffer,直接返回原始数据 if (config.responseType === 'arraybuffer') { resolve(resdate) return } // 按 JSON 处理 const code = resdate.code || 200 const msg = errorCode[code] || resdate.msg || errorCode['default'] if (code === 401) { showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => { if (res.confirm) { store.dispatch('LogOut').then(res => { uni.reLaunch({ url: '/pages/login' }) }) } }) reject('无效的会话,或者会话已过期,请重新登录。') } else if (code === 500) { toast(msg) reject(resdate) } else if (code !== 200) { toast(msg) reject(resdate) } else { resolve(resdate) } }).catch(error => { let { message } = error if (message === 'Network Error') { message = '后端接口连接异常' } else if (message.includes('timeout')) { message = '系统接口请求超时' } else if (message.includes('Request failed with status code')) { message = '系统接口' + message.substr(message.length - 3) + '异常' } toast(message) reject(error) }) }) } export default request