无法使用Apollo Client 3和setContext(apollo-link-context)

时间:2020-03-24 09:45:49

标签: reactjs graphql apollo apollo-client

因此,我尝试将授权标头传递给Apollo Client 3以访问数据库。在当前文档中推荐的方法是创建一个HttpLink对象

const httpLink = new HttpLink({
  uri: "************************",
  fetch
});

,然后使用setContext方法(我认为来自“ http-link-context”):

const authLink = setContext((_, { headers, ...context }) => {
  const token = localStorage.getItem("userToken");
  return {
    headers: {
      ...headers,
      ...(token
        ? { Authorization: `Bearer ${token}` }
        : `Bearer *************************`)
    },
    ...context
  };
});

然后将对象移植在一起,并将它们作为“链接”对象传递给新的ApolloClient:

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: authLink.concat(httpLink)
});

但是,不幸的是,当我这样做时,我收到一条错误消息

Uncaught (in promise) Error: GraphQL error: Missing authorization header.

当我检查请求标头时,看不到授权标头。

其他人是否能够使它成功启动并运行?

3 个答案:

答案 0 :(得分:1)

非常令人讨厌的是,他们在Apollo文档中给出的示例未显示setContext的导入,因此使用最新版本时,不应从“ http-link-context”导入所需的包,而应从“ @ apollo / link-context”导入版本的Apollo(或仍为Apollo 3)。使用当前程序包可以正常工作。

答案 1 :(得分:1)

我认为他们在那里更新了包含setContext的文档:

    import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
    import { setContext } from '@apollo/client/link/context';
    
    const httpLink = createHttpLink({
      uri: '/graphql',
    });
    
    const authLink = setContext((_, { headers }) => {
      // get the authentication token from local storage if it exists
      const token = localStorage.getItem('token');
      // return the headers to the context so httpLink can read them
      return {
        headers: {
          ...headers,
          authorization: token ? `Bearer ${token}` : "",
        }
      }
    });
    
    const client = new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache()
    });

您不再需要分别安装@ apollo / link-context,所有内容现在都与apollo 3.0捆绑在一起。 [参考]:https://www.apollographql.com/docs/react/networking/authentication

答案 2 :(得分:1)

第一个阿波罗链接上下文现在为@ apollo / client / link / context

第二次:您可以在apolloclient中使用标头

const client = new ApolloClient({
    cache,
  uri: 'http://localhost:4000/graphql',
  headers: {
    authorization: localStorage.getItem('token') || '',
    'client-name': 'Space Explorer [web]',
    'client-version': '1.0.0',
  },
  // or authLink because its return Headers
  ...authLink
});