首页 > 解决方案 > 从本地存储竞争问题设置授权标头?

问题描述

Apollo 客户端建议使用以下代码设置身份验证标头,其中本地存储的数据显示为同步函数调用。

import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

const httpLink = createHttpLink({
  uri: '/graphql',
});

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 client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

在这一行中,

const token = localStorage.getItem('token');

我们主要使用 async/await 从本地存储中获取数据,在这种情况下 authLink 将是异步函数,对吗?例如:

const authLink = setContext(async (_, { headers }) => {

我相信这意味着,

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

这条线在我们完成异步 httpLink 函数调用之前运行,这不是种族问题吗?承诺完成后,阿波罗会将 httpLink 分配给 authLink.concat 吗?

标签: apolloapollo-client

解决方案


推荐阅读