使用 Ferry 和 Flutter 添加标头以进行请求

Hen*_*elo 4 dart graphql flutter

这是我第一次使用 Ferry 发出 GraphQL 请求。我的 GraphQL Server 有一些查询需要 HTTP 标头进行授权。

我需要能够在初始化客户端后添加标头。

客户端.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;
}
Run Code Online (Sandbox Code Playgroud)

主.dart

void main() async{
  final client = await initClient();
  GetIt.I.registerLazySingleton<Client>(() => client);
  runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)

请求文件

    client.request(Req).listen((response) {
      print(response.graphqlErrors); // It will return an error because theres no header with the token
      print(response.data);
    });
Run Code Online (Sandbox Code Playgroud)

Mat*_*out 8

以下是向 Ferry GraphQL 客户端请求添加标头的简单示例。在此示例中,我们将授权承载令牌添加到请求中。

defaultHeaders通过在创建对象时将对象添加到参数来添加标头HttpLink

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 只是一个更新,我已经切换到 [Artemis](https://pub.dev/packages/artemis/versions/7.1.1-beta.1),我更喜欢它,因为它更好地将前端与后端解耦,并且总体而言更加灵活,可根据用例进行定制。 (2认同)