apollo - 从本地存储竞争问题设置授权标头?
问题描述
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 吗?
解决方案
推荐阅读
- javascript - Reactjs / Material UI => 当主题已经渲染时,MuiTheme 和重新渲染不起作用
- python - 按多个值过滤列
- c - 在 C 中添加双变量不会在打印时给出小数
- python - 使用索引python读取csv文件
- angular - 使用 loadTranslations 更新 Angular 语言后如何更新常量
- xml - 如何在android studio的gridLayout中的每个列和行块之后创建可见边界?
- javascript - addEventListener mouseenter not
- javascript - NodeJs - 显示来自数据库的数据
- python - 有没有办法根据列表的长度设置 SQL 查询中的变量数量?
- typescript - 从 prism-react-renderer 导入时,Typescript 无法正确键入 PrismJS