站点信息,保存 数据
This commit is contained in:
30
ln_jq_app/lib/common/token_interceptor.dart
Normal file
30
ln_jq_app/lib/common/token_interceptor.dart
Normal file
@@ -0,0 +1,30 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:ln_jq_app/storage_service.dart';
|
||||
|
||||
/// 专门用于处理和添加 Token 的拦截器
|
||||
class TokenInterceptor extends Interceptor {
|
||||
// 定义您想要使用的 Token Key
|
||||
final String tokenKey;
|
||||
|
||||
// 构造函数,允许外部传入自定义的 Key,默认为 'Authorization'
|
||||
TokenInterceptor({this.tokenKey = 'Authorization'});
|
||||
|
||||
@override
|
||||
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
||||
// 从 StorageService 中获取已保存的 token
|
||||
final String? token = StorageService.to.token;
|
||||
|
||||
// 如果 token 存在,就添加到请求头中
|
||||
if (token != null && token.isNotEmpty) {
|
||||
// 检查请求头中是否已存在这个key,避免重复添加
|
||||
if (!options.headers.containsKey(tokenKey)) {
|
||||
// 使用我们自定义的 key 添加 token
|
||||
options.headers[tokenKey] = token;
|
||||
}
|
||||
}
|
||||
|
||||
// 调用 handler.next(options) 以继续执行请求
|
||||
// 这一步至关重要,否则请求会被中断
|
||||
super.onRequest(options, handler);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user