我试图拦截将授权密钥放入头文件的请求。对于使用Api
类所做的每个请求,我都要这样做。但出于某种原因,我得到了一个401错误。我检查了头,发现钥匙不见了。有人知道,我需要更改什么才能得到请求头中的键?
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;
}
}
...
在我的颤振应用程序中,我调用了这样的响应:
api.get(url);
发布于 2022-08-10 11:28:50
请尝试下面的东西,如果你需要更多的许可,让我知道。
例如,您可以调用api方法。
await apis.call("apiMethods", formData,'get').then((resData) async {});
//此处,如何添加自动化令牌
dio.options.headers["Authorization"] = "Bearer $authToken";
api.dart拦截器方法
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: (DioError e, handler) {
printLog("::: Api error : $e");
return handler.next(e);
},
));
}
https://stackoverflow.com/questions/73304720
复制相似问题