我正在使用 apollo-client
库从我的 Graphql
服务器查询数据。通过 apollo 轮询功能,每 5 秒向服务器发送一些查询。
是否有一种通用方法可以将自定义 header 添加到我的轮询客户端发送的所有请求中?
最佳答案
两种解决方案
有两种方法可以做到这一点。一种是快速简便,适用于有一定限制的特定查询,另一种是通用解决方案,更安全,适用于多个查询。
快速简便的解决方案
优势
- 很快
- 而且……简单
当您配置查询时,您可以使用其 options
字段对其进行配置,该字段有一个 context
字段。 context
的值将由网络链处理。 context
本身不会发送到服务器,但如果您向其添加 headers
字段,它将在 HTTP 请求中使用。
示例:
const someQuery = graphql(gql`query { ... }`, {
options: {
context: {
headers: {
"x-custom-header": "pancakes" // this header will reach the server
}
},
// ... other options
}
})
使用网络链接中间件的一般解决方案
使用 Apollo,您可以添加一个 Apollo Link 作为中间件,并根据查询操作设置的 context
向请求添加自定义 header 。
来自文档:
Apollo Client has a pluggable network interface layer, which can let you configure how queries are sent over HTTP
阅读更多关于 Apollo Link, the network link and Middleware concepts 的信息.
优点:
- 中间件的逻辑可以被任何 graphql 操作使用(你设置条件)
- 您的查询不需要“关心”或了解 HTTP header
- 在决定是否向请求中添加 header 以及添加哪些 header 之前,您可以进行更多处理。
- 还有更多..
设置上下文
与快速简便的解决方案相同,只是这次我们不直接设置headers
:
{
options: {
context: {
canHazPancakes: true //this will not reach the server
}
}
}
添加中间件
Apollo 有一个特定的中间件用于设置上下文 apollo-link-context
(同样可以用更通用的中间件实现)。
import {setContext} from 'apollo-link-context'
//...
const pancakesLink = setContext((operation, previousContext) => {
const { headers, canHazPancakes } = previousContext
if (!canHazPancakes) {
return previousContext
}
return {
...previousContext,
headers: {
...headers,
"x-with-pancakes": "yes" //your custom header
}
}
})
不要忘记将它连接到您的 http 链接之前某处的网络链
const client = new ApolloClient({
// ...
link: ApolloLink.from([
pancakesLink,
<yourHttpLink>
])
})
文档中还有另一个有用的示例:using a middleware for authentication .
就是这样!你现在应该从服务器上拿一些煎饼。希望这会有所帮助。
关于javascript - 将自定义 header 添加到 apollo 客户端轮询请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48558681/