import { useMemberStore } from '@/stores' import { Decrypt, Encrypt } from './utils' import { userLoginApi } from '@/services/home' //引入 pinia 。。登录后将信息储存到pinia const baseUrl = import.meta.env.VITE_SERVE export const imgUrl = `${import.meta.env.VITE_IMG_URL}/file/show?filePath=` export const mediaUrl = `${import.meta.env.VITE_MEDIA}/file/show?filePath=` let temp_request: any[] = [], is_freshing = false const httpInterceptor = { //拦截前触发 invoke(options: UniApp.RequestOptions) { //拼接地址 if (!options.url.startsWith('http')) { options.url = baseUrl + options.url } //请求时间 options.timeout = 10000 options.header = { ...options.header, 'source-client': 'miniapp', } //判断如果请求体里有data//且data不为空 if ('data' in options) { //如果包含data属性 options.data = { data: Encrypt(JSON.stringify(options.data)) } } console.log(options) //添加 token 请求头标识 const memberStore = useMemberStore() // const token = memberStore.profile?.token const token = memberStore.token options.header.Authorization = token ? `Bearer ${token}` : '' }, } uni.addInterceptor('request', httpInterceptor) uni.addInterceptor('uploadFile', httpInterceptor) // export default baseUrl //请求函数 /** * @param UniApp.RequestOptions * @returns Promise */ interface Data { code: string msg: string data: T } export const http = (option: UniApp.RequestOptions) => { uni.showLoading() let params_ = option // console.log(option?.data) return new Promise>((resolve, reject) => { uni.request({ ...option, success(res) { //获取状态码 // res.ststusCode if (res.statusCode >= 200 && res.statusCode < 300) { //访问成功 // eslint-disable-next-line no-debugger resolve(JSON.parse(Decrypt(res.data))) // resolve(res.data as Data) } else if (res.statusCode === 401) { //当token过期后弹出确认再次登录的提示框 //如果点击确定再次调用登录接口 if (!is_freshing) { //调用登录接口 refresh() } else { resolve( new Promise((resol) => { temp_request.push(() => { resol(http(params_)) }) }), ) } //清理用户信息 //跳转到登录页 const memberStore = useMemberStore() memberStore.clearProfile() uni.navigateTo({ url: '/src/pages/index/index', }) reject(res) } else { // (res.data as Data).msg uni.showToast({ icon: 'none', title: (res.data as Data).msg || '请求错误请稍后再试', }) reject(res) } }, //响应失败,网络断开 fail(err) { console.log(err) uni.showToast({ icon: 'none', title: '网络错误', }) //网络错误 }, complete() { uni.hideLoading({ noConflict: true, }) }, }) }) } const refresh = () => { is_freshing = true uni.login({ success: (res) => { if (res.errMsg === 'login:ok') { //调用登录接口 //获取到code后 loginHttp(res.code) } }, }) } const loginHttp = async (code: string) => { const res = await userLoginApi({ code: code }) //登录成功后需要将 is_refresh 状态改为false //然后回调 if (res.data) { console.log(res.data) } else { is_freshing = false temp_request.map((cb) => cb()) // 清空temp_request temp_request = [] } }