diff --git a/src/store/authentication.js b/src/store/authentication.js index 82c2e83..ffbf71c 100644 --- a/src/store/authentication.js +++ b/src/store/authentication.js @@ -1,19 +1,16 @@ import axios from 'axios'; const state = { - user: null, isAuthenticated: false, token: null, }; const mutations = { - setUser(state, {user, token}) { - state.user = user; + setUser(state, {token}) { state.isAuthenticated = true; state.token = token; }, clearUser(state) { - state.user = null; state.isAuthenticated = false; state.token = null; }, @@ -23,20 +20,13 @@ const actions = { async login({commit}, credentials) { const response = await axios.post('/api/login', credentials); if (response.status === 200) { - commit('setUser', {user: response.data.username, token: response.data.token}); + commit('setUser', {token: response.data.token}); } return response; }, logout({commit}) { commit('clearUser'); }, - async fetchUserProfile({commit}) { - const response = await axios.get('/api/user-profile'); - if (response.status === 200) { - commit('setUser', {user: response.data}); - } - return response; - }, }; const getters = { diff --git a/src/views/authentication/Profile.vue b/src/views/authentication/Profile.vue index 812dbff..a59b8f7 100644 --- a/src/views/authentication/Profile.vue +++ b/src/views/authentication/Profile.vue @@ -2,8 +2,12 @@ import {onMounted, ref} from 'vue'; import 'element-plus/dist/index.css'; import {useStore} from 'vuex'; +import axios from "axios"; +import {ElMessage} from "element-plus"; +import { useRouter } from 'vue-router'; const store = useStore(); +const router = useRouter(); const nickname = ref(''); const phoneNumber = ref(''); @@ -13,15 +17,31 @@ const role = ref(''); const createdAt = ref(''); onMounted(async () => { - const response = await store.dispatch('authentication/fetchUserProfile'); - if (response.status === 200) { - const user = response.data; - nickname.value = user.nickname; - phoneNumber.value = user.phoneNumber; - email.value = user.email; - department.value = user.department; - role.value = user.role; - createdAt.value = user.createdAt; + try { + // 从Vuex中获取JWT token + const token = store.getters['authentication/token']; + if (!token) { + store.commit('authentication/logout'); + router.push('/login'); + } + + // 发送请求并附带token参数 + const response = await axios.get(`/api/userProfile?token=${token}`); + + if (response.status === 200) { + const user = response.data; + nickname.value = user.nickname; + phoneNumber.value = user.phoneNumber; + email.value = user.email; + department.value = user.department; + role.value = user.role; + createdAt.value = user.createdAt; + } else { + ElMessage.error("获取用户信息失败,请重试"); + } + } catch (error) { + console.error('Error fetching user profile:', error); + ElMessage.error("获取用户信息失败,请重试"); } });