登录功能接入数据库

This commit is contained in:
2025-08-19 14:45:17 +08:00
parent 6857d2c3de
commit 1ceaeb9214
8 changed files with 635 additions and 46 deletions
+21 -23
View File
@@ -3,27 +3,25 @@ import { login as loginApi, getUserInfo as getUserInfoApi, logout as logoutApi }
import ENV_CONFIG from '@/config/env'
interface LoginForm {
username: string
account: string
password: string
}
interface UserInfo {
id: number
username: string
account: string
name: string
avatar?: string
role: string
}
interface ApiResponse<T> {
code: number
message: string
data: T
phone?: string
sex?: number
qq?: string
wechat?: string
create_time?: number
}
interface LoginResponse {
token: string
userInfo: UserInfo
user_info: UserInfo
}
const useUserStore = defineStore('user', {
@@ -48,29 +46,29 @@ const useUserStore = defineStore('user', {
// 用户登录
async userLogin(loginForm: LoginForm) {
try {
const response = await loginApi(loginForm) as unknown as ApiResponse<LoginResponse>
const response = await loginApi(loginForm) as unknown as LoginResponse
// 假设API返回格式为 { code: 200, data: { token: string, userInfo: UserInfo } }
if (response.code === 200 && response.data) {
const { token, userInfo } = response.data
// 后端返回格式为 { token: string, user_info: UserInfo }
if (response && response.token && response.user_info) {
const { token, user_info } = response
// 保存登录状态
this.token = token
this.userInfo = userInfo
this.userInfo = user_info
this.isLogin = true
// 保存到 localStorage
localStorage.setItem(ENV_CONFIG.TOKEN_KEY, token)
localStorage.setItem(ENV_CONFIG.USER_INFO_KEY, JSON.stringify(userInfo))
localStorage.setItem(ENV_CONFIG.USER_INFO_KEY, JSON.stringify(user_info))
return userInfo
return user_info
} else {
throw new Error(response.message || '登录失败')
throw new Error('登录响应数据格式错误')
}
} catch (error: any) {
// 处理不同类型的错误
if (error.response?.data?.message) {
throw new Error(error.response.data.message)
if (error.response?.data?.msg) {
throw new Error(error.response.data.msg)
} else if (error.message) {
throw new Error(error.message)
} else {
@@ -104,10 +102,10 @@ const useUserStore = defineStore('user', {
if (token && userInfoStr) {
try {
// 验证token是否有效
const response = await getUserInfoApi() as unknown as ApiResponse<UserInfo>
if (response.code === 200 && response.data) {
const response = await getUserInfoApi() as unknown as UserInfo
if (response && response.id) {
this.token = token
this.userInfo = response.data
this.userInfo = response
this.isLogin = true
} else {
// token无效,清除本地存储但不调用logout API