美文网首页
806.【前端】apollo graphql动态配置header

806.【前端】apollo graphql动态配置header

作者: 七镜 | 来源:发表于2023-09-27 06:23 被阅读0次

一、问题背景

以前在使用apollo graphql时,会在client中配置好headers。可是想配置headers里的Authorization时,面临着一个问题:用户没有登录的时候,获取不到Authorization;只有在用户登录之后,才获取的道Authorization。这就意味着,咱们的clinet中,需要动态配置headers。

原来是这样弄的:

export const client = new ApolloClient({
    headers: {
        "Authorization": mapNameGetTokenAccess(),
    },
    cache: new InMemoryCache(),
    uri: API_GQL_SERVER
});

二、解决方案

import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  cache: new InMemoryCache(),
  uri: "/graphql"
});

client.query({
  query: MY_QUERY,
  context: {
    // example of setting the headers with context per operation
    headers: {
      special: "Special header value"
    }
  }
});

具体可查看官方教程:https://www.apollographql.com/docs/react/networking/advanced-http-networking/#overriding-options

改完之后,就可以实现:在需要的时候重新配置headers里的Authorization了。

相关文章

网友评论

      本文标题:806.【前端】apollo graphql动态配置header

      本文链接:https://www.haomeiwen.com/subject/zkufbdtx.html