onRequest method

  1. @override
void onRequest(
  1. RequestOptions options,
  2. RequestInterceptorHandler handler
)

Called when the request is about to be sent.

Implementation

@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
  // 检查是否有自定义Token配置
  final tokenConfig = options.extra['tokenConfig'] as TokenConfig?;

  // 如果明确设置为不使用Token,则跳过
  if (tokenConfig != null && !tokenConfig.useToken) {
    handler.next(options);
    return;
  }

  // 获取Token
  String? token;
  if (tokenConfig?.customToken != null) {
    token = tokenConfig!.customToken;
  } else {
    token = TokenManager.instance.getToken();
  }

  // 如果有Token,则添加到请求头
  if (token != null && token.isNotEmpty) {
    final headerValue = formatConfig.format(token);
    options.headers[formatConfig.headerKey] = headerValue;
  }

  handler.next(options);
}