refactor: ♻️ 优化请求工具类
This commit is contained in:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user