创建后更新 Apollo 客户端身份验证链接

Tom*_*Tom 5 javascript apollo-client

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

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),
});
Run Code Online (Sandbox Code Playgroud)

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

如果不实例化新的 Apollo Client,我将如何做到这一点?

Tom*_*Tom 2

我使用 Apollo Links 找到了不止一种解决此问题的方法。

我采用的方法(因为我的应用程序的身份验证的结构方式)是setContext使用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,
});
Run Code Online (Sandbox Code Playgroud)

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

还有一个用于刷新令牌的特定链接