目标
我想填充我的 Authorization
带有访问 token 的 header 。我想将该访问 token 存储在 Apollo 缓存中为 Auth0明确声明不要在本地存储中存储访问 token (我不知道为什么 Apollo Client docs 似乎认为没问题)。
如果做不到这一点,我想安全地存储我的访问 token ,并能够将它添加到每个 Apollo 客户端对 Apollo 服务器的请求。
const apolloClient = withApollo(({ctx, headers, initialState}) => {
const cache = new InMemoryCache();
// Code here to access local cache.
return new ApolloClient({
cache,
link: new HttpLink({
uri: <apollo server endpoint>,
headers: {
Authorization: `Bearer ${accessToken}`,
'Access-Control-Allow-Origin': 'http://localhost:3000/',
...headers
},
credentials: 'include'
}),
typeDefs,
resolvers
})
})
class MyApp extends App {
render() {
const { Component, pageProps, apollo } = this.props;
return (
<ApolloProvider client={apollo}>
<Component {...pageProps} />
</ApolloProvider>
);
}
}
export default apolloClient(MyApp);
试过
localStorage
来自 withApollo
功能,但它是 SSR 的,所以我无法访问它。我打算使用 localStorage
设置一个 bool 值来检查 withApollo
函数,因此它会知道在重定向后访问 token 已添加到 apollo 缓存中。 Authorization
标题。但是我在设置初始状态覆盖登录功能中设置的缓存时遇到了问题。 其他想法
ctx
中传递访问 token 论点,但我对 Next.js 不够熟悉,无法确定这是否是有效的方法。 withApollo
来自组件的功能,但这似乎不可能。 问题
fetch
polyfill,这是否适合这种情况?如果是这样,那将如何运作? withApollo
怎么办HOC 工作以及为什么需要使用 Next.js 工作?我已经阅读了这背后的一些代码,但我从根本上不明白为什么需要它。 最佳答案
我能够找到我的问题的解决方案。我只是没有完全理解 Apollo Client 以及如何使用所有必需的包。
解决方案
我用过 setContext
来自 apollo-link-context
图书馆。它是 link
的一部分Apollo Client 提供的一组库,用于在开始 graphql 操作后自定义网络请求。我在 setContext
中设置了标题功能。像这样:
const authLink = setContext((_, { headers }) => {
// It is also possible to use the local storage method in here.
const data = cache.readQuery({
query: ACCESS_TOKEN
});
return {
headers: {
...headers,
authorization: accessToken ? `Bearer ${data.accessToken}` : ""
}
}
});
以下为withApollo
外功能。const httpLink = new HttpLink({
uri: '<server uri>',
});
以下是withApollo
里面的功能。return new ApolloClient({
cache,
link: authLink.concat(httpLink),
typeDefs,
resolvers
})
有关如何操作的文档 setContext
是 here而`apollo-link-context' 的文档是 here .
关于authorization - Apollo 客户端 + Next.js - 向客户端请求添加授权 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58076206/