From c02c8a2ac8aec8a1b506180fd9090175e0fb5d82 Mon Sep 17 00:00:00 2001 From: weiwei Date: Thu, 15 May 2025 18:51:24 +0800 Subject: [PATCH] 1 --- src/sheep/utils/request.ts | 154 ++++++++----------------------------- 1 file changed, 31 insertions(+), 123 deletions(-) diff --git a/src/sheep/utils/request.ts b/src/sheep/utils/request.ts index a87a3e2..14a8021 100644 --- a/src/sheep/utils/request.ts +++ b/src/sheep/utils/request.ts @@ -1,38 +1,13 @@ import Request from "luch-request" -import { isEmpty } from "radash" -import isDevEnv from "./isDevEnv" import { router, constant } from "@@/index" import { userApi } from "../api" +import { isEmpty } from "radash" +import isDevEnv from "./isDevEnv" import { getAppInfo } from "@@/utils/getAppInfo" -// 常量定义 const TOKEN_KEY = constant.storageConstant.TOKEN const USER_INFO_KEY = constant.storageConstant.USERINFO -// Loading 状态管理 -const LoadingInstance = { - target: null, - count: 0, -} - -// 关闭加载提示 -function closeLoading() { - if (LoadingInstance.count > 0) LoadingInstance.count-- - if (LoadingInstance.count === 0) uni.hideLoading() -} - -// 显示加载提示 -function showLoading(message: string) { - LoadingInstance.count++ - if (LoadingInstance.count === 1) { - uni.showLoading({ - title: message, - mask: true, - fail: () => uni.hideLoading(), - }) - } -} - // 读取token并处理Authorization请求头 const getAuthHeader = (tokenStorage: any) => { if (isDevEnv()) { @@ -45,8 +20,7 @@ const getAuthHeader = (tokenStorage: any) => { async function handleZzdLogin(): Promise { try { uni.showLoading({ title: "加载中...", mask: true }) - const params = new URL(window.location.href).searchParams - const token = params.get("uabaseToken") + const token = new URL(window.location.href).searchParams.get("uabaseToken") if (!token) { uni.showToast({ title: "用户凭证已失效,请重新进入智慧后勤应用", icon: "none", duration: 6000 }) @@ -69,8 +43,8 @@ async function handleZzdLogin(): Promise { } return false } - } catch (error) { - uni.showToast({ title: "登录错误", icon: "none" }) + } catch (error: any) { + uni.showToast({ title: error, icon: "none" }) return false } finally { uni.hideLoading() @@ -81,6 +55,7 @@ async function handleZzdLogin(): Promise { async function handleShLogin(): Promise { try { uni.showLoading({ title: "登录中...", mask: true }) + const userInfo = await (window as any).CP2.getUserInfo() if (userInfo.code == 0 || !userInfo.data.accountId || !userInfo.data.sessionId) { uni.showToast({ title: "获取诗画用户信息失败", icon: "none" }) @@ -89,23 +64,13 @@ async function handleShLogin(): Promise { const { accountId, sessionId } = userInfo.data const response = await userApi.authsh({ accountId, sessionId }) - // const response = await userApi.authsh({ accountId: "67e790d6a95d5a7b507e53dd", sessionId: "67fdff553cbc284e352ebb4d" }) // 测试 + // const response = await userApi.authsh({ accountId: "67e790d6a95d5a7b507e53dd", sessionId: "68215b03a95d5a4899d20cb4" }) // 测试 if (response.code == 0) { uni.setStorageSync(TOKEN_KEY, { accessToken: response.data.accessToken }) const { data: userData } = await userApi.userInfo() uni.setStorageSync(USER_INFO_KEY, userData) uni.showToast({ title: "登录成功", icon: "none" }) - return true - } else { - uni.removeStorageSync(TOKEN_KEY) - uni.removeStorageSync(USER_INFO_KEY) - if (response.msg == "token已失效") { - uni.showToast({ title: "用户凭证已失效,请退出并重新进入智慧后勤应用", icon: "none", duration: 6000 }) - } else { - uni.showToast({ title: response.msg || "登录失败", icon: "none" }) - } - return false // if (response.data == -1) { // uni.showToast({ title: "您的设备需要信任验证", icon: "none" }) @@ -126,6 +91,17 @@ async function handleShLogin(): Promise { // } // return false // } + + return true + } else { + uni.removeStorageSync(TOKEN_KEY) + uni.removeStorageSync(USER_INFO_KEY) + if (response.msg == "token已失效") { + uni.showToast({ title: "用户凭证已失效,请退出并重新进入智慧后勤应用", icon: "none", duration: 6000 }) + } else { + uni.showToast({ title: response.msg || "登录失败", icon: "none" }) + } + return false } } catch (error) { uni.showToast({ title: "登录错误", icon: "none" }) @@ -169,42 +145,6 @@ async function checkAndRefreshToken(tokenStorage: any) { } } -// 处理错误响应 -function handleErrorResponse(response: any) { - if (!response.config?.custom?.showError) return - - switch (response.data.code) { - case 401: - // 处理未授权情况 - setTimeout(() => { - uni.removeStorageSync(TOKEN_KEY) - uni.removeStorageSync(USER_INFO_KEY) - }, 500) - break - case 424: - // 处理token过期 - autoLogin() - break - default: - uni.showToast({ - title: response.data.msg || "服务器开小差啦,请稍后再试~", - icon: "none", - mask: true, - }) - } -} - -// 处理成功提示 -function handleSuccessMessage(response: any) { - const { data, config } = response - if (data.code === 0 && data.message && config?.custom?.showSuccess) { - uni.showToast({ - title: config.custom.successMsg || data.message, - icon: "none", - }) - } -} - // 创建请求实例 const http = new Request({ baseURL: import.meta.env.VITE_API_URL, @@ -220,7 +160,6 @@ const http = new Request({ successMsg: "", // 成功消息 showError: true, // 显示失败消息 默认显示 errorMsg: "", // 失败提醒 默认使用后端返回信息 - showLoading: true, // 显示请求时loading模态框 默认显示 loadingMsg: "加载中", // loading提醒文字 auth: false, // 需要授权才能请求 默认放开 }, @@ -228,35 +167,26 @@ const http = new Request({ // 请求拦截器 http.interceptors.request.use(async (config) => { + console.log("config", config) + const tokenStorage = uni.getStorageSync(TOKEN_KEY) - const config_header: any = config?.header || {} + 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 (import.meta.env.VITE_IS_TOC === "true") config_header["CLIENT-TOC"] = "Y" - // 处理 loading - if (config.custom?.showLoading) { - showLoading(config.custom.loadingMsg) - } - - // 不需要设置认证头的接口 + // 不需要设置认证头的接口路径 const skipAuthUrls = ["/thirdparty/thirdPartyOAth2", "/sys/auth/refresh-token", "/auth/oauth2/token"] // 判断是否需要设置认证头 - const needAuth = !skipAuthUrls.some((url) => config.url?.startsWith(url)) - - if (needAuth) { + if (!skipAuthUrls.some((url) => config.url?.startsWith(url))) { if (!isEmpty(tokenStorage)) { - // token过期刷新检查 + // token存在,token过期刷新检查 await checkAndRefreshToken(tokenStorage) const authHeader = getAuthHeader(tokenStorage) - if (authHeader) { - config_header.Authorization = authHeader - } + if (authHeader) config_header.Authorization = authHeader } else { // token不存在,则发起登录 await autoLogin() @@ -264,9 +194,7 @@ http.interceptors.request.use(async (config) => { // 登录后重新获取token const newTokenStorage = uni.getStorageSync(TOKEN_KEY) const authHeader = getAuthHeader(newTokenStorage) - if (authHeader) { - config_header.Authorization = authHeader - } + if (authHeader) config_header.Authorization = authHeader } } @@ -276,12 +204,9 @@ http.interceptors.request.use(async (config) => { // 响应拦截器 http.interceptors.response.use( async (response) => { - // 关闭loading - if (response.config?.custom?.showLoading) { - closeLoading() - } + console.log("response", response) - // OAuth2 token请求特殊处理 + // 账号密码登录响应结果特殊处理 if (response.config.url === "/auth/oauth2/token") { return Promise.resolve({ code: 0, @@ -290,22 +215,10 @@ http.interceptors.response.use( }) } - // 错误处理和错误提示 - if (response.data.code !== 0) { - handleErrorResponse(response) - return Promise.resolve(response.data) - } - - // 成功提示 - handleSuccessMessage(response) - return Promise.resolve(response.data) }, async (error) => { - // 处理 loading - if (error.config?.custom?.showLoading) { - closeLoading() - } + console.log("error", error) // 处理 424 错误(token过期) if (error.statusCode === 424) { @@ -315,7 +228,6 @@ http.interceptors.response.use( uni.removeStorageSync(USER_INFO_KEY) uni.showToast({ title: "登录已过期,请重新登录", icon: "none" }) router.jump("/pages/test/login") - return false } else { await autoLogin() } @@ -323,11 +235,7 @@ http.interceptors.response.use( // 显示错误信息 if (error?.data?.msg) { - uni.showToast({ - title: error.data.msg, - icon: "none", - mask: true, - }) + uni.showToast({ title: error.data.msg, icon: "none", mask: true }) } return Promise.resolve(error.data) },