如何从 Apollo Client 的 useQuery 获取响应头

How to get response header from useQuery of Apollo Client

我根本找不到办法做到这一点。有谁知道这是否受支持?谢谢。

ApolloClient 发出请求的方法,以及使用它们的 React Hooks,作为对数据实际获取方式的抽象。它可能来自通过 HTTP 的远程服务器、缓存、直接针对模式执行请求等。因此,它们不会首先公开有关如何获取数据的任何信息,包括 transport-specific 类似 HTTP 的信息 headers.

如果您需要访问此信息,适当的位置是在 Link 中,您可以将其添加到 HttpLink 中——可以是现有的 ContextLinkErrorLink,或者您自己滚动的一些自定义 Link。如果您在 error-handling 上下文中执行此操作,那么 ErrorLink 将是您最好的选择,如评论中所建议的那样。

HttpLink 将来自服务器的原始响应注入到所有 Link 所使用的上下文 object 中(参见 here). Assuming you're using the default fetch API as the fetcher, this response will be a Response object.

所以你可以这样做:

const link = onError(({ graphQLErrors, networkError, operation }) => {
  const { response } = operation.getContext();
  const { headers, status } = response;
  
  // do something with the headers
});