refactor: ♻️ 优化请求工具类
This commit is contained in:
18
src/enums/ResultCodeEnum.ts
Normal file
18
src/enums/ResultCodeEnum.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* 响应码枚举
|
||||
*/
|
||||
export const enum ResultCodeEnum {
|
||||
/**
|
||||
* 成功
|
||||
*/
|
||||
SUCCESS = "00000",
|
||||
/**
|
||||
* 错误
|
||||
*/
|
||||
ERROR = "B0001",
|
||||
|
||||
/**
|
||||
* 令牌无效或过期
|
||||
*/
|
||||
TOKEN_INVALID = "A0230",
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineStore } from "pinia";
|
||||
import AuthAPI from "@/api/auth";
|
||||
import UserAPI, { UserInfo } from "@/api/user";
|
||||
import { setToken, clearToken } from "@/utils/auth";
|
||||
|
||||
export const useUserStore = defineStore("user", () => {
|
||||
// 确保 token 是响应式的
|
||||
@@ -8,10 +9,22 @@ export const useUserStore = defineStore("user", () => {
|
||||
const userInfo = ref<UserInfo | null>(null);
|
||||
|
||||
// 登录
|
||||
const login = async (username: string, password: string) => {
|
||||
const { tokenType, accessToken } = await AuthAPI.login(username, password);
|
||||
token.value = `${tokenType} ${accessToken}`; // Bearer token
|
||||
uni.setStorageSync("token", token.value);
|
||||
const login = (username: string, password: string) => {
|
||||
AuthAPI.login(username, password)
|
||||
.then((res) => {
|
||||
token.value = ` ${res.accessToken}`; // Bearer token
|
||||
setToken(token.value);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (error.action === "TOKEN_INVALID") {
|
||||
// 处理 Token 失效,比如弹出登录提示框,而不是直接跳转
|
||||
console.log("Token 已失效,请重新登录");
|
||||
// 例如:uni.navigateTo({ url: '/pages/login/index' });
|
||||
} else {
|
||||
// 处理其他错误
|
||||
console.error("请求失败", error.message);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 获取用户信息
|
||||
@@ -25,7 +38,7 @@ export const useUserStore = defineStore("user", () => {
|
||||
await AuthAPI.logout();
|
||||
userInfo.value = null;
|
||||
token.value = ""; // 清空 token
|
||||
uni.removeStorageSync("token"); // 从本地缓存移除 token
|
||||
clearToken(); // 从本地缓存移除 token
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
19
src/utils/auth.ts
Normal file
19
src/utils/auth.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
const TOKEN_KEY = "app-token";
|
||||
|
||||
function getToken(): string {
|
||||
return uni.getStorageSync(TOKEN_KEY) || "";
|
||||
}
|
||||
|
||||
function setToken(token: string) {
|
||||
return uni.setStorageSync(TOKEN_KEY, token);
|
||||
}
|
||||
|
||||
function clearToken() {
|
||||
return uni.removeStorageSync(TOKEN_KEY);
|
||||
}
|
||||
|
||||
function isLogin(): boolean {
|
||||
return !!getToken();
|
||||
}
|
||||
|
||||
export { getToken, setToken, clearToken, isLogin };
|
||||
@@ -1,20 +1,48 @@
|
||||
import { getToken, clearToken } from "@/utils/auth";
|
||||
import { ResultCodeEnum } from "@/enums/ResultCodeEnum";
|
||||
|
||||
export default function request<T>(options: UniApp.RequestOptions): Promise<T> {
|
||||
const token = uni.getStorageSync("token"); // 从本地缓存获取 token
|
||||
// H5 使用 VITE_APP_BASE_API 作为代理路径,其他平台使用 VITE_APP_API_URL 作为请求路径
|
||||
let baseApi = import.meta.env.VITE_APP_API_URL;
|
||||
// #ifdef H5
|
||||
baseApi = import.meta.env.VITE_APP_BASE_API;
|
||||
// #endif
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.request({
|
||||
...options,
|
||||
url: `${import.meta.env.VITE_APP_BASE_API}${options.url}`,
|
||||
url: `${baseApi}${options.url}`,
|
||||
header: {
|
||||
...options.header,
|
||||
Authorization: token,
|
||||
Authorization: getToken() ? `Bearer ${getToken()}` : "", // 添加 Bearer 前缀
|
||||
},
|
||||
success: (response) => {
|
||||
console.log("success response", response);
|
||||
const resData = response.data as ResponseData<T>;
|
||||
|
||||
// 业务状态码 00000 表示成功
|
||||
if (resData.code === "00000") {
|
||||
if (resData.code === ResultCodeEnum.SUCCESS) {
|
||||
resolve(resData.data);
|
||||
} else {
|
||||
}
|
||||
// 令牌失效或过期处理
|
||||
else if (resData.code === ResultCodeEnum.TOKEN_INVALID) {
|
||||
uni.showToast({
|
||||
title: resData.msg || "令牌无效或过期",
|
||||
icon: "none",
|
||||
duration: 2000,
|
||||
});
|
||||
|
||||
clearToken();
|
||||
|
||||
// 此处不强制跳转到登录页,可以让调用方决定下一步操作
|
||||
reject({
|
||||
message: resData.msg || "令牌无效或过期",
|
||||
code: resData.code,
|
||||
action: "TOKEN_INVALID", // 提供一个 action 用于后续调用方判断
|
||||
});
|
||||
}
|
||||
// 其他业务处理失败
|
||||
else {
|
||||
uni.showToast({
|
||||
title: resData.msg || "业务处理失败",
|
||||
icon: "none",
|
||||
@@ -27,6 +55,7 @@ export default function request<T>(options: UniApp.RequestOptions): Promise<T> {
|
||||
}
|
||||
},
|
||||
fail: (error) => {
|
||||
console.log("fail error", error);
|
||||
uni.showToast({
|
||||
title: "网络请求失败",
|
||||
icon: "none",
|
||||
|
||||
Reference in New Issue
Block a user