简体   繁体   English

使用带有 Flutter 的 Ferry 向请求添加标头

[英]Add headers to request using Ferry with Flutter

it's my first time using Ferry to make GraphQL requests.这是我第一次使用 Ferry 发出 GraphQL 请求。 My GraphQL Server has some queries that need an HTTP header for authorization.我的 GraphQL 服务器有一些查询需要 HTTP header 进行授权。

I need to be able to add the header after initializing the client.初始化客户端后,我需要能够添加 header。

client.dart :客户端.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 : main.dart

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

request file :请求文件

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

Here is a simple example for adding headers to the Ferry GraphQL client requests.这是一个向 Ferry GraphQL 客户端请求添加标头的简单示例。 In this example, we add an Authorization Bearer Token to the request.在此示例中,我们向请求中添加了 Authorization Bearer Token。

The headers are added by adding an object to the defaultHeaders parameter on creation of the HttpLink object.在创建HttpLink object 时,通过将 object 添加到defaultHeaders参数来添加标头。

graphql_service.dart 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;
}

Try this implementation work for me!为我尝试这个实施工作!

save auth_link.dar from graphql_fluttergraphql_flutter 保存 auth_link.dar

Working example工作示例

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM