【问题标题】:Apollo GraphQL: Change default Header INSIDE React Child ComponentApollo GraphQL:更改默认标题 INSIDE React 子组件
【发布时间】:2018-12-22 22:50:17
【问题描述】:

我正在尝试将我的 Apollo Graph QL 客户端 INSIDE 的默认标题更改为一个反应组件,但我根本无法在文档中找到任何内容。因此,在我的 index.js 中,我按照描述创建和链接我的客户端,并添加一个 JWT 令牌标头。但是如果我想更改我的 React 组件中的标题怎么办。例如,我想在 reauthenticate 时替换 Token。

在 Axios 中,您可以简单地对此进行操作。

axios.defaults.headers.common['Auth-Token'] = 'foo bar';

如何使用 React Apollo 做类似的事情?这是我的 index.js 的重要部分

const httpLink = createHttpLink({
    uri: 'https://somesecureapi',
});

const authLink = setContext((_, { headers }) => {

const token = localStorage.getItem('token');
return {
    headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : "",
    }
}
});

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

我尝试导出客户端,然后将其导入组件,创建一个新链接并更改旧链接,但这不起作用。

必须有一些更简单的方法。任何建议

【问题讨论】:

    标签: reactjs redux graphql apollo


    【解决方案1】:

    createHttpLink 接受fetch 选项,您可以在其中自定义您希望fetch 的行为方式。一个简单的实现可能如下所示:

    import { ApolloProvider, graphql } from "react-apollo";
    import { ApolloClient } from "apollo-client";
    import { InMemoryCache } from "apollo-cache-inmemory";
    import { ApolloLink } from "apollo-link";
    import { createHttpLink } from "apollo-link-http";
    
    const customFetch = (uri, options) => {
      return fetch(uri, {
        ...options,
        headers: {
          ...options.headers,
          "x-custom-header": "custom value"
        }
      });
    };
    
    const fetchLink = createHttpLink({
      uri: "https://graphql-pokemon.now.sh",
      fetch: customFetch
    });
    
    const client = new ApolloClient({
      link: ApolloLink.from([fetchLink]),
      cache: new InMemoryCache()
    });
    

    正如您在customFetch 中看到的,我添加了x-custom-header"custom value"。这将应用于使用此客户端的所有查询。但是,我也在为fetch 选项传播options.headers,因此任何出现的标头都将通过。

    在我们的组件中,我们可以像这样传递额外的标头:

    const WrappedPokemon = graphql(PokemonQuery, {
      options: {
        context: { headers: { "x-another-custom-header": "another custom value" } }
      },
      props: ({ data }) => ({
        loading: data.loading,
        pokemon: data.pokemon || {}
      })
    })(Pokemon);
    

    与上面的不同,这个额外的标题只存在于这个查询中。

    我在codesandbox做了一个简单的实现,帮助大家理解实现。

    结果如下所示:

    【讨论】:

      猜你喜欢
      • 2018-09-29
      • 2019-01-25
      • 2018-04-12
      • 2020-10-30
      • 2018-06-29
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      相关资源
      最近更新 更多