0

我正在尝试实现一个 Dio 拦截器,这样我就可以在我的代码中使用它。

我将在很多地方使用这个拦截器。所以我认为将它放入一个类或接口中是有意义的,无论哪个最好,然后扩展或实现它我的子类。

到目前为止我有这个:

class AppInterceptor {
  Dio dio = Dio();
  AppInterceptor() {
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (Options options) async {
        var token = await getAuthorizationToken();

        options.headers["Authorization"] = 'Bearer $token';
        return options;

    }, onResponse: (Response response) {
      // Finally, the string is parsed into a JSON object.
      //print(response.toString());
      return response;
    }, onError: (DioError e) {
      print('somthing went wrong');
      // Do something with response error
      return e; //continue
    }));
  }
}

如何在子类中使用它来进行 http 调用?

在尝试进行 http 调用时,我尝试了类似的方法:

 Response response = await AppInterceptor.dio.post(Global.functionsUrl+'/auth/linkuseraccount/', data: {'hey': 'hello'});
  print(response);

每次都失败 Unhandled Exception: DioError [DioErrorType.RESPONSE]: Http status error [403]

从我的后端,我可以看出它失败了,因为拦截器没有传入身份验证标头。

我该怎么办?

4

0 回答 0