首页 > 解决方案 > URQL - GraphQL 如何获取响应标头

问题描述

当我对 GraphQL 服务器进行查询时,我想读取 http 响应标头中设置的信息。

当我使用 urql 客户端执行查询时,我只得到这些信息:

/** Resulting data from an [operation]{@link Operation}. */
export interface OperationResult<Data = any> {
    /** The [operation]{@link Operation} which has been executed. */
    operation: Operation;
    /** The data returned from the Graphql server. */
    data?: Data;
    /** Any errors resulting from the operation. */
    error?: CombinedError;
    /** Optional extensions return by the Graphql server. */
    extensions?: Record<string, any>;
    /** Optional stale flag added by exchanges that return stale results. */
    stale?: boolean;
}

有没有办法获取响应标头?

标签: graphqlurql

解决方案


您可以在提供的客户端(如果它对您的应用程序是全局的)中使用fetch包装器,也可以在组件中的特定客户端中使用包装器,其fetch选项如下:

  const client = createClient({
    url: `https://example.org/graphql`,
    fetch: (...args) =>
      fetch(...args).then((response) => {
        const myHeader = response.headers.get('my-header');
        if (myHeader) {
          /* do stuff */
        }

        return response;
      }),
    fetchOptions: { credentials: 'include' },
    …
  });


推荐阅读