Files
t/main.js
T
2026-05-04 00:43:20 +08:00

100 lines
2.3 KiB
JavaScript

import App from './App'
import uView from '@/uni_modules/uview-ui'
Vue.use(uView)
// ================== Vue2 逻辑 ================== //
// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
// 初始化 Vue2 配置
Vue.config.productionTip = false
App.mpType = 'app'
// 创建 Vue 实例
const app = new Vue({ ...App })
app.$mount()
// #endif
// ================== Vue3 逻辑 ================== //
// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
return { app }
}
// #endif
// ================== 全局请求拦截器 ================== //
uni.addInterceptor('request', {
invoke(args) {
// 1. 添加认证信息
const token = uni.getStorageSync('uni_id_token')
if (token) {
args.header = {
...args.header,
'X-Cloud-Token': token,
// 异步获取设备信息(避免阻塞)
'X-Device-Id': getApp().globalData.deviceId || 'unknown'
}
}
// 2. 添加请求超时配置
if (!args.timeout) {
args.timeout = 10000 // 默认10秒超时
}
// 3. 生产环境移除调试输出
if (process.env.NODE_ENV === 'development') {
console.log('[请求拦截]', args.url, args.header)
}
return args
},
fail(err) {
// 1. 网络错误处理
if (err.errMsg.includes('fail abort')) {
uni.showToast({ title: '请求取消', icon: 'none' })
}
// 2. 超时处理
else if (err.errMsg.includes('timeout')) {
uni.showToast({ title: '网络超时,请重试', icon: 'none' })
}
// 3. Token失效处理
else if (err.errMsg.includes('401') || err.errMsg.includes('TOKEN')) {
handleTokenExpired()
}
// 4. 其他错误
else {
uni.showToast({ title: '网络异常', icon: 'none' })
}
}
})
// 独立处理Token过期的函数
function handleTokenExpired() {
uni.showModal({
title: '登录过期',
content: '请重新登录',
showCancel: false,
success: () => {
uni.removeStorageSync('uni_id_token')
uni.reLaunch({ url: '/pages/login' })
}
})
}
// 在应用启动时预加载设备信息
export function initDeviceInfo() {
uni.getSystemInfo({
success: (res) => {
getApp().globalData = getApp().globalData || {}
getApp().globalData.deviceId = res.deviceId
}
})
}