feat: 大量升级,v2.0.0

This commit is contained in:
菲鸽
2024-04-17 15:32:15 +08:00
parent 09fbee72aa
commit 28caa1dea3
37 changed files with 233 additions and 297 deletions

View File

@@ -1,2 +1,3 @@
export { routeInterceptor } from './route'
export { requestInterceptor } from './request'
export { prototypeInterceptor } from './prototype'

View File

@@ -0,0 +1,13 @@
export const prototypeInterceptor = {
install() {
// 解决低版本手机不识别 array.at() 导致运行报错的问题
if (typeof Array.prototype.at !== 'function') {
// eslint-disable-next-line no-extend-native
Array.prototype.at = function (index: number) {
if (index < 0) return this[this.length + index]
if (index >= this.length) return undefined
return this[index]
}
}
},
}

View File

@@ -1,13 +1,16 @@
/* eslint-disable no-param-reassign */
import qs from 'qs'
import { useUserStore } from '@/store'
import { platform } from '@/utils/platform'
export type CustomRequestOptions = UniApp.RequestOptions & {
query?: Record<string, any>
/** 出错时是否隐藏错误提示 */
hideErrorToast?: boolean
} & IUniUploadFileOptions // 添加uni.uploadFile参数类型
// 请求基地址
const baseURL = import.meta.env.VITE_SERVER_BASEURL
// 请求基地址
const baseUrl = import.meta.env.VITE_SERVER_BASEURL
// 拦截器配置
const httpInterceptor = {
@@ -22,19 +25,19 @@ const httpInterceptor = {
options.url += `?${queryStr}`
}
}
// 1. 非 http 开头需拼接地址
// 非 http 开头需拼接地址
if (!options.url.startsWith('http')) {
options.url = baseURL + options.url
options.url = baseUrl + options.url
// TIPS: 如果需要对接多个后端服务,也可以在这里处理,拼接成所需要的地址
}
// 2. 请求超时
// 1. 请求超时
options.timeout = 10000 // 10s
// 3. 添加小程序端请求头标识
// 2. (可选)添加小程序端请求头标识
options.header = {
platform: 'mp-weixin', // 可选与 uniapp 定义的平台一致,告诉后台来源
platform, // 可选与 uniapp 定义的平台一致,告诉后台来源
...options.header,
}
// 4. 添加 token 请求头标识
// 3. 添加 token 请求头标识
const userStore = useUserStore()
const { token } = userStore.userInfo as unknown as IUserInfo
if (token) {

View File

@@ -21,7 +21,7 @@ const isDev = import.meta.env.DEV
const navigateToInterceptor = {
// 注意这里的url是 '/' 开头的,如 '/pages/index/index',跟 'pages.json' 里面的 path 不同
invoke({ url }: { url: string }) {
console.log(url) // /pages/route-interceptor/index?name=feige&age=30
// console.log(url) // /pages/route-interceptor/index?name=feige&age=30
const path = url.split('?')[0]
let needLoginPages: string[] = []
// 为了防止开发时出现BUG这里每次都获取一下。生产环境可以移到函数外性能更好
@@ -30,18 +30,17 @@ const navigateToInterceptor = {
} else {
needLoginPages = _needLoginPages
}
console.log(needLoginPages.includes(path))
if (needLoginPages.includes(path)) {
const isLogin = isLogined()
if (isLogin) {
return true
}
const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
uni.navigateTo({ url: redirectRoute })
return false
const isNeedLogin = needLoginPages.includes(path)
if (!isNeedLogin) {
return true
}
return true
const hasLogin = isLogined()
if (hasLogin) {
return true
}
const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
uni.navigateTo({ url: redirectRoute })
return false
},
}