fix(mining-app): 修复登录后API请求token未更新的问题
问题原因: ApiClient使用内存缓存的token,登录后虽然保存到SharedPreferences, 但ApiClient的内存缓存未更新,导致后续请求仍使用旧token或无token。 解决方案: 移除内存缓存,每次请求都从SharedPreferences读取最新token, 确保登录后立即生效。 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
c35d90e94f
commit
a0229e653e
|
|
@ -5,7 +5,6 @@ import '../error/exceptions.dart';
|
||||||
|
|
||||||
class ApiClient {
|
class ApiClient {
|
||||||
final Dio dio;
|
final Dio dio;
|
||||||
String? _accessToken;
|
|
||||||
|
|
||||||
ApiClient({required this.dio}) {
|
ApiClient({required this.dio}) {
|
||||||
dio.options = BaseOptions(
|
dio.options = BaseOptions(
|
||||||
|
|
@ -21,27 +20,17 @@ class ApiClient {
|
||||||
// 添加请求拦截器,自动注入 token
|
// 添加请求拦截器,自动注入 token
|
||||||
dio.interceptors.add(InterceptorsWrapper(
|
dio.interceptors.add(InterceptorsWrapper(
|
||||||
onRequest: (options, handler) async {
|
onRequest: (options, handler) async {
|
||||||
if (_accessToken == null) {
|
// 每次请求都从存储中读取最新的 token,确保登录后立即生效
|
||||||
// 从存储中加载 token
|
final prefs = await SharedPreferences.getInstance();
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final token = prefs.getString('access_token');
|
||||||
_accessToken = prefs.getString('access_token');
|
if (token != null && token.isNotEmpty) {
|
||||||
}
|
options.headers['Authorization'] = 'Bearer $token';
|
||||||
if (_accessToken != null) {
|
|
||||||
options.headers['Authorization'] = 'Bearer $_accessToken';
|
|
||||||
}
|
}
|
||||||
handler.next(options);
|
handler.next(options);
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
void setAccessToken(String? token) {
|
|
||||||
_accessToken = token;
|
|
||||||
}
|
|
||||||
|
|
||||||
void clearAccessToken() {
|
|
||||||
_accessToken = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<Response> get(
|
Future<Response> get(
|
||||||
String path, {
|
String path, {
|
||||||
Map<String, dynamic>? queryParameters,
|
Map<String, dynamic>? queryParameters,
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue