无法从ApolloClient

时间:2019-06-30 15:16:00

标签: javascript authentication graphql react-apollo apollo-client

我正在使用ApolloGraphQL实现React身份验证。

上下文:
在signin.js中,当用户单击“提交”按钮并将其设置为Localstorage时,我将生成令牌。
然后,我在App.js中检索令牌,可以将其传递给GraphQL,以便可以在server.js中对其进行检索。

问题:
用户单击提交按钮后,我可以在以下位置看到新一代令牌:开发人员工具>应用程序>本地存储。 但是它在App.js中为“客户端令牌”返回“空”
当我再次登录时,我看到先前生成的令牌是“客户端令牌”的值,这意味着它没有从LocalStorage获取更新的令牌。

显然,由于这个原因,“服务器端令牌”第一次为空,而第二次登录时返回先前生成的令牌。

app / client / src / components / signin.js

    handleSubmit = (event, SignIn)  => {
        event.preventDefault();
        SignIn().then(({ data }) => {
                localStorage.setItem('token', data.SignIn.token);
                this.clearState();
        })
    }  

app / client / src / app.js

  //initiating the ApolloClient
const client = new ApolloClient({
  uri: 'http://localhost:4000/graphql',

  fetchOptions: {
    credentials: 'include'
  },
//adding token to the localstorage
  request: operation => {
  const token = localStorage.getItem('token');

  operation.setContext({
      headers:{
          authorization: token
      }
    })
    console.log(`client side token ${token}`);
   },
 //catching the most common network error, if any
  onError: ({ networkError }) => {
    if(networkError){
      console.log('Network Error', networkError);
      }
  }
});

server.js

const app = express();
app.use(async (req, res, next) => {
const token = req.headers['authorization'];
console.log(`server side token: ${token}`);
  next();
});

1 个答案:

答案 0 :(得分:0)

您需要某种身份验证中间件,因为apollo客户端中的请求仅在构造上被调用,我相信这就是为什么当您重新加载页面时localStorage具有先前的令牌的原因。

import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink, concat } from 'apollo-link';

const httpLink = new HttpLink({ uri: '/graphql' });

const authMiddleware = new ApolloLink((operation, forward) => {
  // add the authorization to the headers
  operation.setContext({
    headers: {
      authorization: localStorage.getItem('token') || null,
    }
  });

  return forward(operation);
})

const client = new ApolloClient({
  link: concat(authMiddleware, httpLink),
});

有关更多详细信息,请参见https://www.apollographql.com/docs/react/advanced/network-layer/#middleware