接口修改
This commit is contained in:
1 parent
4452435ecf
commit
7ba2bfce2b
5 files changed
+6022
-4833
No files matched your search
+186
-111
@@ -5,8 +5,19 @@ import { userApi } from "@@/api"
|
||||
import { router, constant } from "@@/index"
|
||||
import isDevEnv from "./isDevEnv"
|
||||
|
||||
const options = {
|
||||
// 显示操作成功消息 默认不显示
|
||||
// 定义常量
|
||||
const TOKEN_KEY = constant.storageConstant.TOKEN
|
||||
const USER_INFO_KEY = constant.storageConstant.USERINFO
|
||||
const REFRESH_TOKEN_URL = "/auth/oauth2/token?grant_type=refresh_token"
|
||||
|
||||
// 定义类型
|
||||
interface LoadingInstance {
|
||||
target: any
|
||||
count: number
|
||||
}
|
||||
|
||||
// 默认请求配置
|
||||
const defaultOptions = {
|
||||
showSuccess: false,
|
||||
// 成功提醒 默认使用后端返回值
|
||||
successMsg: "",
|
||||
@@ -22,16 +33,19 @@ const options = {
|
||||
auth: false,
|
||||
}
|
||||
|
||||
let LoadingInstance = {
|
||||
// Loading 管理
|
||||
const LoadingInstance: LoadingInstance = {
|
||||
target: null,
|
||||
count: 0,
|
||||
}
|
||||
|
||||
// 关闭 loading
|
||||
function closeLoading() {
|
||||
if (LoadingInstance.count > 0) LoadingInstance.count--
|
||||
if (LoadingInstance.count === 0) uni.hideLoading()
|
||||
}
|
||||
|
||||
// 创建请求实例
|
||||
const http = new Request({
|
||||
baseURL: import.meta.env.VITE_API_URL,
|
||||
timeout: 8000,
|
||||
@@ -41,61 +55,122 @@ const http = new Request({
|
||||
"Content-Type": "application/json;charset=UTF-8",
|
||||
},
|
||||
withCredentials: true,
|
||||
custom: options,
|
||||
custom: defaultOptions,
|
||||
})
|
||||
|
||||
http.interceptors.request.use(
|
||||
(config) => {
|
||||
const tokenKey = constant.storageConstant.TOKEN
|
||||
const tokenStorage = uni.getStorageSync(tokenKey)
|
||||
const config_header: any = config?.header
|
||||
// 添加终端类型
|
||||
const isToc = import.meta.env.VITE_IS_TOC
|
||||
if (isToc === "true") {
|
||||
config_header["CLIENT-TOC"] = "Y"
|
||||
}
|
||||
config_header["TENANT-ID"] = "1"
|
||||
if (
|
||||
config.url != "/sys/auth/refresh-token" &&
|
||||
tokenStorage &&
|
||||
tokenStorage.access_token &&
|
||||
config_header &&
|
||||
isDevEnv()
|
||||
) {
|
||||
config_header.Authorization = `Bearer ${tokenStorage.access_token}`
|
||||
}
|
||||
if (
|
||||
config.url != "/sys/auth/refresh-token" &&
|
||||
tokenStorage &&
|
||||
tokenStorage.accessToken &&
|
||||
config_header &&
|
||||
!isDevEnv()
|
||||
) {
|
||||
console.log("aaaa", tokenStorage)
|
||||
// 处理请求头 Authorization
|
||||
const getAuthHeader = (tokenStorage: any) => {
|
||||
if (isDevEnv()) {
|
||||
return tokenStorage?.access_token ? `Bearer ${tokenStorage.access_token}` : null
|
||||
}
|
||||
return tokenStorage?.accessToken?.tokenValue ? `Bearer ${tokenStorage.accessToken.tokenValue}` : null
|
||||
}
|
||||
|
||||
config_header.Authorization = `Bearer ${tokenStorage.accessToken.tokenValue}`
|
||||
// 请求拦截器
|
||||
http.interceptors.request.use((config) => {
|
||||
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
|
||||
const config_header: any = config?.header || {}
|
||||
|
||||
// 设置通用请求头
|
||||
config_header["TENANT-ID"] = "1"
|
||||
if (import.meta.env.VITE_IS_TOC === "true") {
|
||||
config_header["CLIENT-TOC"] = "Y"
|
||||
}
|
||||
|
||||
// 设置认证头
|
||||
if (config.url !== "/sys/auth/refresh-token") {
|
||||
const authHeader = getAuthHeader(tokenStorage)
|
||||
if (authHeader) {
|
||||
config_header.Authorization = authHeader
|
||||
}
|
||||
if (config.custom && config.custom.showLoading) {
|
||||
LoadingInstance.count++
|
||||
LoadingInstance.count === 1 &&
|
||||
uni.showLoading({
|
||||
title: config.custom.loadingMsg,
|
||||
}
|
||||
|
||||
// 处理 loading
|
||||
if (config.custom?.showLoading) {
|
||||
LoadingInstance.count++
|
||||
if (LoadingInstance.count === 1) {
|
||||
uni.showLoading({
|
||||
title: config.custom.loadingMsg,
|
||||
mask: true,
|
||||
fail: () => uni.hideLoading(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return config
|
||||
}, Promise.reject)
|
||||
|
||||
// 定义响应处理的辅助函数
|
||||
const responseHelpers = {
|
||||
// 处理错误响应
|
||||
handleErrorResponse(response: any) {
|
||||
if (!response.config?.custom?.showError) return
|
||||
|
||||
switch (response.data.code) {
|
||||
case 401:
|
||||
this.handleUnauthorized()
|
||||
break
|
||||
default:
|
||||
uni.showToast({
|
||||
title: response.data.msg || "服务器开小差啦,请稍后再试~",
|
||||
icon: "none",
|
||||
mask: true,
|
||||
fail: () => {
|
||||
uni.hideLoading()
|
||||
},
|
||||
})
|
||||
}
|
||||
return config
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
|
||||
// 处理未授权情况
|
||||
handleUnauthorized() {
|
||||
setTimeout(() => {
|
||||
uni.removeStorageSync(TOKEN_KEY)
|
||||
uni.removeStorageSync(USER_INFO_KEY)
|
||||
router.jump("/pages/tabbar/my", {}, 2)
|
||||
}, 500)
|
||||
},
|
||||
|
||||
// 处理成功提示
|
||||
handleSuccessMessage(response: any) {
|
||||
const { data, config } = response
|
||||
if (data.code === 200 && data.message && config?.custom?.showSuccess) {
|
||||
uni.showToast({
|
||||
title: config.custom.successMsg || data.message,
|
||||
icon: "none",
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
// 处理登录过期
|
||||
handleLoginExpired() {
|
||||
uni.removeStorageSync(TOKEN_KEY)
|
||||
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
|
||||
router.jump("/pages/test/login")
|
||||
},
|
||||
|
||||
// 检查并刷新token
|
||||
async checkAndRefreshToken(tokenStorage: any) {
|
||||
const { refresh_token, expiresTime } = tokenStorage
|
||||
if (!refresh_token || !expiresTime) return
|
||||
|
||||
const now = new Date().getTime()
|
||||
const remain = expiresTime - now
|
||||
if (remain <= 1000 * 60 * 20) {
|
||||
const refreshData = await userApi.refreshToken({ refreshToken: refresh_token })
|
||||
if (!isEmpty(refreshData.data)) {
|
||||
uni.setStorageSync(TOKEN_KEY, refreshData.data)
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
// 响应拦截器
|
||||
http.interceptors.response.use(
|
||||
async (response) => {
|
||||
response.config && response.config.custom && response.config.custom.showLoading && closeLoading()
|
||||
// 关闭loading
|
||||
if (response.config?.custom?.showLoading) {
|
||||
closeLoading()
|
||||
}
|
||||
|
||||
// OAuth2 token请求特殊处理
|
||||
if (response.config.url === "/auth/oauth2/token") {
|
||||
return Promise.resolve({
|
||||
code: 0,
|
||||
@@ -103,83 +178,83 @@ http.interceptors.response.use(
|
||||
msg: null,
|
||||
})
|
||||
}
|
||||
|
||||
// 错误处理
|
||||
if (response.data.code !== 0) {
|
||||
if (response.config && response.config.custom && response.config.custom.showError) {
|
||||
switch (response.data.code) {
|
||||
case 401:
|
||||
setTimeout(() => {
|
||||
const tokenKey = constant.storageConstant.TOKEN
|
||||
const userInfoKey = constant.storageConstant.USERINFO
|
||||
uni.removeStorageSync(tokenKey)
|
||||
uni.removeStorageSync(userInfoKey)
|
||||
router.jump("/pages/tabbar/my", {}, 2)
|
||||
}, 500)
|
||||
break
|
||||
default:
|
||||
uni.showToast({
|
||||
title: response.data.msg || "服务器开小差啦,请稍后再试~",
|
||||
icon: "none",
|
||||
mask: true,
|
||||
})
|
||||
break
|
||||
}
|
||||
return Promise.resolve(response.data)
|
||||
}
|
||||
}
|
||||
if (
|
||||
response.data.code === 200 &&
|
||||
response.data.message !== "" &&
|
||||
response.config &&
|
||||
response.config.custom &&
|
||||
response.config.custom.showSuccess
|
||||
) {
|
||||
uni.showToast({
|
||||
title: response.config.custom.successMsg || response.data.message,
|
||||
icon: "none",
|
||||
})
|
||||
responseHelpers.handleErrorResponse(response)
|
||||
return Promise.resolve(response.data)
|
||||
}
|
||||
|
||||
// 成功提示
|
||||
responseHelpers.handleSuccessMessage(response)
|
||||
|
||||
// 登录过期处理
|
||||
if (response.data.code === 1) {
|
||||
const tokenKey = constant.storageConstant.TOKEN
|
||||
uni.removeStorageSync(tokenKey)
|
||||
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
|
||||
router.jump("/pages/test/login")
|
||||
responseHelpers.handleLoginExpired()
|
||||
}
|
||||
const tokenKey = constant.storageConstant.TOKEN
|
||||
const tokenStorage = uni.getStorageSync(tokenKey)
|
||||
if (!isEmpty(tokenStorage) && response.config.url != "/sys/auth/refresh-token") {
|
||||
const { refresh_token, expiresTime } = tokenStorage
|
||||
if (!isEmpty(refresh_token) && !isEmpty(expiresTime)) {
|
||||
const now = new Date().getTime()
|
||||
const remain = expiresTime - now
|
||||
if (remain <= 1000 * 60 * 20) {
|
||||
const _pa = { refreshToken: refresh_token }
|
||||
const refreshData = await userApi.refreshToken(_pa)
|
||||
if (!isEmpty(refreshData.data)) {
|
||||
uni.setStorageSync(tokenKey, refreshData.data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Token 刷新检查
|
||||
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
|
||||
if (!isEmpty(tokenStorage) && response.config.url !== "/sys/auth/refresh-token") {
|
||||
await responseHelpers.checkAndRefreshToken(tokenStorage)
|
||||
}
|
||||
|
||||
return Promise.resolve(response.data)
|
||||
},
|
||||
(error) => {
|
||||
if (error.statusCode == 424 && isDevEnv()) {
|
||||
const tokenKey = constant.storageConstant.TOKEN
|
||||
const userInfoKey = constant.storageConstant.USERINFO
|
||||
uni.removeStorageSync(tokenKey)
|
||||
uni.removeStorageSync(userInfoKey)
|
||||
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
|
||||
isDevEnv() ? router.jump("/pages/test/login") : undefined
|
||||
return false
|
||||
|
||||
// 错误拦截器
|
||||
async (error) => {
|
||||
// 处理 424 错误(token过期)
|
||||
if (error.statusCode === 424) {
|
||||
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
|
||||
|
||||
if (isDevEnv()) {
|
||||
// 开发环境直接清除token并跳转登录
|
||||
uni.removeStorageSync(TOKEN_KEY)
|
||||
uni.removeStorageSync(USER_INFO_KEY)
|
||||
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
|
||||
router.jump("/pages/test/login")
|
||||
return false
|
||||
}
|
||||
|
||||
// 生产环境尝试刷新token
|
||||
if (tokenStorage?.refreshToken?.tokenValue) {
|
||||
try {
|
||||
const refreshData = await request({
|
||||
url: REFRESH_TOKEN_URL,
|
||||
method: "POST",
|
||||
data: JSON.stringify({
|
||||
scope: "server",
|
||||
refresh_token: tokenStorage.refreshToken.tokenValue,
|
||||
}),
|
||||
header: {
|
||||
Authorization: "Basic " + window.btoa(import.meta.env.VITE_OAUTH2_APP_CLIENT),
|
||||
"content-type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
})
|
||||
|
||||
if (refreshData.code === 0) {
|
||||
// 刷新成功,更新token并重试请求
|
||||
uni.setStorageSync(TOKEN_KEY, refreshData.data)
|
||||
const config = error.config
|
||||
config.header!.Authorization = `Bearer ${refreshData.data.accessToken.tokenValue}`
|
||||
return http.request(config)
|
||||
}
|
||||
} catch (refreshError) {
|
||||
console.error("Token refresh failed:", refreshError)
|
||||
}
|
||||
}
|
||||
}
|
||||
let errorMessage = error.data.msg
|
||||
if (error !== undefined) {
|
||||
|
||||
// 显示错误信息
|
||||
if (error?.data?.msg) {
|
||||
uni.showToast({
|
||||
title: errorMessage || "",
|
||||
title: error.data.msg,
|
||||
icon: "none",
|
||||
mask: true,
|
||||
})
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user