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

2023-09-27  本文已影响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了。

上一篇 下一篇

猜你喜欢

热点阅读