[英]How to use localStorage with apollo-client and reactjs?
[英]looking for a way to pass the token to apollo-client via cookies not localstorage
我确实从apollo-boost
切换到apollo-client
并且我确实检查了文档,我确实发现他们通过localStorage
设置了令牌,但问题是我的本地存储中没有任何令牌我唯一的令牌是在浏览器cookies
所以基本上我正在寻找一种将令牌从 cookies 传递给apollo-client
的方法
const httpLink = createUploadLink({
uri: 'http://localhost:9999',
credentials: 'include'
});
const authMiddleware = new ApolloLink((operation, forward) => {
// Retrieve the authorization token from local storage.
const token = localStorage.getItem('token');
console.log(token); //undefined
// Use the setContext method to set the HTTP headers.
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : ''
}
});
// Call the next link in the middleware chain.
return forward(operation);
});
const client = new ApolloClient({
// link: authLink.concat(httpLink),
link: concat(authMiddleware, httpLink),
cache: new InMemoryCache()
});
您可以按照此处关于如何从 cookies 中检索数据的步骤操作: Get cookie with react
因此,如果您使用 js-cookie,您的 authMiddleware function 将如下所示:
import Cookies from 'js-cookie';
const authMiddleware = new ApolloLink((operation, forward) => {
// Retrieve the authorization token from browser cookies.
const token = Cookies.get('token');
console.log(token);
// Use the setContext method to set the HTTP headers.
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : ''
}
});
// Call the next link in the middleware chain.
return forward(operation);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.