feat: 完善登录等接口鉴权
This commit is contained in:
@@ -1,6 +1,10 @@
|
||||
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
|
||||
import axios from 'axios';
|
||||
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
|
||||
import { envConfig } from '../config/env';
|
||||
|
||||
// Token 存储键名(与 auth service 保持一致)
|
||||
const TOKEN_KEY = 'access_token';
|
||||
|
||||
// 创建 axios 实例
|
||||
const apiClient: AxiosInstance = axios.create({
|
||||
baseURL: envConfig.apiBaseUrl,
|
||||
@@ -13,11 +17,11 @@ const apiClient: AxiosInstance = axios.create({
|
||||
// 请求拦截器
|
||||
apiClient.interceptors.request.use(
|
||||
(config) => {
|
||||
// 可以在这里添加 token 等认证信息
|
||||
// const token = localStorage.getItem('token')
|
||||
// if (token) {
|
||||
// config.headers.Authorization = `Bearer ${token}`
|
||||
// }
|
||||
// 自动添加 token 到请求头
|
||||
const token = localStorage.getItem(TOKEN_KEY);
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
if (envConfig.debug) {
|
||||
console.log('请求:', config.method?.toUpperCase(), config.url);
|
||||
@@ -50,8 +54,13 @@ apiClient.interceptors.response.use(
|
||||
if (error.response) {
|
||||
switch (error.response.status) {
|
||||
case 401:
|
||||
// 未授权,可以跳转到登录页
|
||||
// window.location.href = '/login'
|
||||
// 未授权,清除 token 并跳转到登录页
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
localStorage.removeItem('user_info');
|
||||
// 避免在登录页重复跳转
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
break;
|
||||
case 403:
|
||||
console.error('没有权限访问该资源');
|
||||
|
||||
Reference in New Issue
Block a user