From 56cc73a295128b5a85b6411186d0b862ba36538d Mon Sep 17 00:00:00 2001 From: mmc <1556375442@qq.com> Date: Mon, 16 Mar 2026 12:40:02 +0800 Subject: [PATCH] =?UTF-8?q?token=E8=BF=87=E6=9C=9F=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/core/network/dio_client.dart | 35 ++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/lib/core/network/dio_client.dart b/lib/core/network/dio_client.dart index dbb1ff41..3ba2dfd1 100644 --- a/lib/core/network/dio_client.dart +++ b/lib/core/network/dio_client.dart @@ -1,8 +1,8 @@ import 'package:dio/dio.dart'; import 'package:maibu_satabot_v2/core/consts/http_api_consts.dart'; - -import '../app/app_user_cubit.dart'; -import '../di/injection.dart'; +import 'package:maibu_satabot_v2/core/app/app_user_cubit.dart'; +import 'package:maibu_satabot_v2/core/di/injection.dart'; +import 'package:maibu_satabot_v2/features/auth/presentation/bloc/auth_cubit.dart'; class DioClient { static Dio create() { @@ -14,26 +14,45 @@ class DioClient { headers: {'Content-Type': 'application/json'}, ), ); + dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true)); + dio.interceptors.add( InterceptorsWrapper( onRequest: (options, handler) { - // 1. 从 GetIt 中获取全局的 AppUserCubit final userCubit = sl(); - - // 2. 从 Cubit 的状态中提取 Token final token = userCubit.state.user?.token; - // 3. 如果 Token 存在,则添加到请求头 if (token != null && token.isNotEmpty) { options.headers['Authorization'] = 'Bearer $token'; } - // 继续发送请求 return handler.next(options); }, + + // ====================== + // ✅ 关键:401 自动拦截 + // ====================== + onResponse: (response, handler) { + return handler.next(response); + }, + + onError: (DioException e, handler) async { + // 401 = token 过期 / 未授权 + if (e.response?.statusCode == 401) { + try { + // 调用 logout 清除本地缓存 + 跳登录 + await sl().logout(); + } catch (ex) { + // 防止报错 + } + } + + return handler.next(e); + }, ), ); + return dio; } }