使用 Ferry 和 Flutter 向请求添加标头

问题描述 投票:0回答:3

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

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

client.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);
    });
flutter dart graphql
3个回答
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;
}

3
投票

为我尝试这个实施工作!

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')}';
}

0
投票

或者,可以通过向请求添加

HttpLinkHeaders
条目来发送每个请求的自定义标头
Context

这是一个简单的例子:

  1. 使用
    HttpLink
    初始化您的客户端:
Future<Client> initClient(Config config) async {
  await Hive.initFlutter();
  final box = await Hive.openBox<dynamic>('graphql');
  final store = HiveStore(box);
  final cache = Cache(store: store);
  final link = HttpLink(config.graphqlServerUrl);
  return Client(link: link, cache: cache);
}
  1. 设置自定义
    Context
    构建器实用程序:
// gql_exec: ^1.0.0+1 <- requires this package
import 'package:gql_exec/gql_exec.dart';

Context buildContextWithHttpHeaders(Map<String, String> headers) {
  return const Context().withEntry(HttpLinkHeaders(headers: headers));
}
  1. 使用标头构建自定义上下文并将其提供给请求构建器:
final token = await getAuthToken();
final headers = { 'Authorization': 'Bearer $token' };
final request = GSomeReq(
    (builder) => builder
      ..fetchPolicy = FetchPolicy.NetworkOnly
      ..context = buildContextWithHttpHeaders(headers),
);

HttpLink
在执行之前将通过请求上下文在内部检索标头:

// gql_http_link: ^1.1.0

Map<String, String> _getHttpLinkHeaders(Request request) {
  ...
  final HttpLinkHeaders? linkHeaders = request.context.entry();
  ...
}

http.BaseRequest _prepareRequest(Request request) {
  ...
  final contextHeaders = _getHttpLinkHeaders(request);
  final headers = {
    "Content-type": "application/json",
    "Accept": "*/*",
    ...defaultHeaders,
    ...contextHeaders,
  };
  ...
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.