From fa26964cbb7387617d14826583c6edd391d57d9c Mon Sep 17 00:00:00 2001 From: zhang96110 Date: Wed, 1 Apr 2026 04:51:24 +0000 Subject: [PATCH] =?UTF-8?q?fix(frontend):=20=E7=BB=99=E5=85=A8=E5=B1=80=20?= =?UTF-8?q?axios=20=E5=AE=9E=E4=BE=8B=E6=B7=BB=E5=8A=A0=20Token=20?= =?UTF-8?q?=E6=8B=A6=E6=88=AA=E5=99=A8=E4=BF=AE=E5=A4=8D=E5=A4=9A=E9=A1=B5?= =?UTF-8?q?=E9=9D=A2=E5=88=97=E8=A1=A8=E5=8A=A0=E8=BD=BD=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 16 个页面文件 100+ 处直接使用 axios 而非封装的 api 实例 - 导致请求不携带 Token,后端返回 401 列表加载失败 - 给全局 axios 默认实例添加请求/响应拦截器自动附加 Token --- frontend/src/api/index.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/frontend/src/api/index.js b/frontend/src/api/index.js index 4457231..84af7ec 100644 --- a/frontend/src/api/index.js +++ b/frontend/src/api/index.js @@ -2,6 +2,31 @@ import axios from 'axios'; import { API_CONFIG } from '../config/api'; import secureStorage, { TOKEN_KEY } from '../utils/secureStorage'; +// 给全局 axios 默认实例添加 Token 拦截器 +// 确保所有页面中直接使用 axios.get/post 的请求也能自动携带 Token +axios.interceptors.request.use(config => { + const token = secureStorage.get(TOKEN_KEY); + if (token) { + config.headers.Authorization = `Bearer ${token}`; + } + return config; +}); + +axios.interceptors.response.use( + response => response, + error => { + if (error.response?.status === 401) { + const currentPath = window.location.pathname; + if (!currentPath.startsWith('/login')) { + secureStorage.remove(TOKEN_KEY); + secureStorage.remove('user'); + window.location.href = '/login'; + } + } + return Promise.reject(error); + } +); + const api = axios.create({ baseURL: API_CONFIG.baseURL, timeout: API_CONFIG.timeout,