繁体   English   中英

寻找一种通过 cookies 而不是 localstorage 将令牌传递给 apollo-client 的方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM