feat:添加登录功能
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import axios from 'axios';
|
||||
import axios, { AxiosHeaders, type AxiosRequestHeaders } from 'axios';
|
||||
import router from '../../router';
|
||||
import { useAuthStore } from '../../stores/auth';
|
||||
|
||||
const baseURL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:4000/api';
|
||||
|
||||
@@ -7,11 +9,33 @@ export const apiClient = axios.create({
|
||||
timeout: 10_000
|
||||
});
|
||||
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
const authStore = useAuthStore();
|
||||
if (authStore.isAuthenticated && authStore.accessToken) {
|
||||
if (config.headers instanceof AxiosHeaders) {
|
||||
config.headers.set('Authorization', `Bearer ${authStore.accessToken}`);
|
||||
} else if (config.headers) {
|
||||
(config.headers as AxiosRequestHeaders).Authorization = `Bearer ${authStore.accessToken}`;
|
||||
} else {
|
||||
config.headers = { Authorization: `Bearer ${authStore.accessToken}` } as AxiosRequestHeaders;
|
||||
}
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response) {
|
||||
console.error('API error', error.response.status, error.response.data);
|
||||
if (error.response.status === 401) {
|
||||
const authStore = useAuthStore();
|
||||
authStore.clearSession();
|
||||
const current = router.currentRoute.value;
|
||||
if (!current.path.startsWith('/auth')) {
|
||||
void router.replace({ name: 'login', query: { redirect: current.fullPath } });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error('Network error', error.message);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user