如何从 Apollo Client 的 useQuery 中获取响应头 [英] How to get response header from useQuery of Apollo Client

查看:83
本文介绍了如何从 Apollo Client 的 useQuery 中获取响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I haven't been able to find a way to do this at all. Does anyone know if this is supported? Thanks.

推荐答案

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

ApolloClient's methods for making requests, and the React hooks that use them, serve as an abstraction over how the data is actually fetched. It could come from a remote server over HTTP, from the cache, from directly executing the request against a schema, etc. As a result, they don't expose any information regarding how the data was fetched in the first place, including transport-specific information like HTTP headers.

如果您需要访问此信息,那么合适的位置应该是在您将其添加到 HTTPLink 的链接中——要么是现有的链接,如 ContextLink 或 ErrorLink,要么是您自己滚动的某个自定义链接.如果您是在错误处理上下文中执行此操作,那么 ErrorLink 将是您最好的选择,正如评论中所建议的那样.

If you need to access this information, the appropriate place to do so would be inside a Link that you'd prepend to your HTTPLink -- either an existing one like a ContextLink or ErrorLink, or some custom Link you roll yourself. If you're doing this in an error-handling context, then ErrorLink would be your best bet, as suggested in the comments.

HttpLink 将来自服务器的原始响应注入到所有链接使用的上下文对象中(参见 此处).假设您使用默认的 fetch API 作为提取器,此响应将是 响应 对象.

HttpLink injects the raw response from the server into the context object used by all Links (see 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
});

这篇关于如何从 Apollo Client 的 useQuery 中获取响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆