【问题标题】:Update Apollo Client auth link after creation创建后更新 Apollo 客户端身份验证链接
【发布时间】:2019-08-12 17:57:12
【问题描述】:

我正在使用令牌通过 Apollo 客户端验证对我的服务器的请求,并复制了文档中提供的以下示例:

const httpLink = createHttpLink({ uri: 'http://0.0.0.0:3003' });

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  };
});

const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
});

这很好用,但最终令牌会过期,我需要更新 Apollo 客户端正在使用的令牌。

如果不实例化新的 Apollo 客户端,我该怎么做?

【问题讨论】:

    标签: javascript apollo-client


    【解决方案1】:

    我发现使用 Apollo Links 解决此问题的方法不止一种。

    我采用的方法(因为我的应用程序的身份验证结构)是使用setContext method from apollo-link-context

    例如

    import { setContext } from "apollo-link-context";
    import { from } from 'apollo-link';
    
    const authMiddleware = setContext((operation, { headers }) => {
      return getToken().then(data => {
        return {
          headers: {
            ...headers,
            authorization: `Bearer ${data.token}` || null,
          }
        };
      });
    });
    
    const apolloClient = new ApolloClient({
      link: from([authMiddleware, httpLink]),
      cache,
    });
    

    现在每次发出请求时都会在标头上设置一个令牌。编写 getToken 函数时要小心,以免每次向 Apollo 发出请求时都调用新令牌。

    还有一个specific Link for refreshing tokens

    【讨论】:

      猜你喜欢
      • 2019-02-28
      • 2018-10-17
      • 1970-01-01
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 2011-04-09
      相关资源
      最近更新 更多