我确实从apollo-boost
切换到apollo-client
,并且确实检查了文档,但确实发现他们通过localStorage
设置了令牌,但问题是我没有任何令牌在我的本地存储中,我唯一拥有的令牌位于浏览器cookies
中,因此基本上我正在寻找一种将令牌从cookie传递到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()
});
答案 0 :(得分:0)
您可以按照此处有关如何从Cookie中检索数据的步骤进行操作:Get cookie with react
因此,如果您使用js-cookie,则authMiddleware函数将如下所示:
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);
});