user16591216
user16591216

Reputation:

Flutter > Dio > Request Interceptor Handler: handler doesn't intercept the request

I'm trying to intercept the requests to put the authorization key in the header. I want this for each request i'm doing with the Api class. But for some reason i get an 401 error. I checked the header and saw that the key is missing. Do someone know, what i need to change to get the key in the header of the requests?

Api api = Api();

class Api extends InterceptorsWrapper {

  static BaseOptions opts = BaseOptions(
    baseUrl: SERVER_IP,
    responseType: ResponseType.json,
    connectTimeout: 5000,
    receiveTimeout: 3000,
  );

  static final dio = Dio(opts);

  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    if (!options.headers.containsKey("Authorization")) {
      var token = secureStorage.getAccessToken();
      options.headers['authorization'] = 'Bearer $token';
    }
    handler.next(options);
    return super.onRequest(options, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    print('ERROR[${err.response?.statusCode}] => PATH: ${err.requestOptions.path}');
    return super.onError(err, handler);
  }

  Future<Response?> get(String url) async {
    try {
      var response = await dio.get(url);
      return response;
    } on DioError catch (e) {
      return null;
    }
  }
...

In my flutter-application i call a response like this:

api.get(url);

Upvotes: 1

Views: 9444

Answers (1)

Nitin Gadhiya
Nitin Gadhiya

Reputation: 427

Please try below things, let me know If you need more clearance.

Example, you can call api method

await apis.call("apiMethods", formData,'get').then((resData) async {});

// Here, how you can add autorization tokens

dio.options.headers["Authorization"] = "Bearer $authToken";

 

api.dart, interceptor Methods

    Apis() {
    //options
    dio.options
      ..baseUrl = env['apiUrl']
      ..validateStatus = (int? status) {
        return status! > 0; //this will always redirect to onResponse method
      }
      ..headers = {
        'Accept': 'application/json',
        'content-type': 'application/json',
      };
    //interceptors
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        printLog("::: Api Url : ${options.uri}");
        printLog("::: Api header : ${options.headers}");
        return handler.next(options);
      },
      onResponse: (response, handler) {
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        printLog("::: Api error : $e");
        return handler.next(e);
      },
    ));
  }

Upvotes: 3

Related Questions