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,
) async {
  // 1. 添加 access token
  String? accessToken = await getATokenFromLocal();
  // print("添加token: $accessToken");
  if (accessToken != null && accessToken.isNotEmpty) {
    options.headers["Authorization"] = "Bearer $accessToken";
  }

  // 2. 添加请求头
  Map<String, String>? headers = await getHeadersFromLocal();
  if (headers != null && headers.isNotEmpty) {
    headers.forEach((key, value) {
      // 添加所有请求头
      options.headers[key] = value;
    });
  }

  handler.next(options);
}