[英]Add headers to request using Ferry with Flutter
這是我第一次使用 Ferry 發出 GraphQL 請求。 我的 GraphQL 服務器有一些查詢需要 HTTP header 進行授權。
初始化客戶端后,我需要能夠添加 header。
客戶端.dart :
Future<Client> initClient() async {
await Hive.initFlutter();
final box = await Hive.openBox<Map<String, dynamic>>("graphql");
await box.clear();
final store = HiveStore(box);
final cache = Cache(store: store);
final link = HttpLink("example.com/");
final client = Client(
link: link,
cache: cache,
);
return client;
}
main.dart :
void main() async{
final client = await initClient();
GetIt.I.registerLazySingleton<Client>(() => client);
runApp(MyApp());
}
請求文件:
client.request(Req).listen((response) {
print(response.graphqlErrors); // It will return an error because theres no header with the token
print(response.data);
});
這是一個向 Ferry GraphQL 客戶端請求添加標頭的簡單示例。 在此示例中,我們向請求中添加了 Authorization Bearer Token。
在創建HttpLink
object 時,通過將 object 添加到defaultHeaders
參數來添加標頭。
graphql_service.dart
import 'package:ferry/ferry.dart';
import 'package:gql_http_link/gql_http_link.dart';
Client initGqlClient(String url) {
final link = HttpLink(
url,
defaultHeaders: {
'Authorization':
'Bearer eyJ0eXAiOi...',
},
);
final client = Client(link: link);
return client;
}
從graphql_flutter 保存 auth_link.dar
import 'dart:async';
import 'package:ferry/ferry.dart';
import 'package:ferry_hive_store/ferry_hive_store.dart';
import 'package:gql_http_link/gql_http_link.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'path_to/auth_link.dart';
Future<Client> initClient() async {
final box = await Hive.openBox("graphql");
await box.clear();
final store = HiveStore(box);
final cache = Cache(store: store);
var httpLink = HttpLink('http://localhost:4000/graphql');
final AuthLink authLink = AuthLink(
getToken: () async => await getBoxToken(),
);
final Link link = authLink.concat(httpLink);
final client = Client(
link: link,
cache: cache,
);
return client;
}
FutureOr<String> getBoxToken() async {
final box = await Hive.openBox("fireToken");
return 'Bearer ${box.get('token')}';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.