两种解决方案
有两种方法可以做到这一点。一种是快速简便,适用于具有一定限制的特定查询,另一种是通用解决方案,更安全,可适用于多个查询。
快速简便的解决方案
优势
当您配置查询时,您可以使用它的 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 向请求添加自定义标头。
来自文档:
Apollo Client 有一个可插拔的网络接口层,它可以让
您可以配置如何通过 HTTP 发送查询
阅读更多关于Apollo Link, the network link and Middleware concepts的信息。
优势:
- 任何graphql操作都可以使用中间件的逻辑(您设置条件)
- 您的查询不需要“关心”或了解 HTTP 标头
- 您可以在决定是否以及向请求中添加哪些标头之前进行更多处理。
- 等等..
设置上下文
同快速简便的解决方案,只是这次我们不直接设置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。
就是这样!您现在应该从服务器获取一些煎饼。希望这会有所帮助。