首页 > 解决方案 > Apollo GraphQL:更改默认标题 INSIDE React 子组件

问题描述

我正在尝试在一个反应​​组件中更改我的 Apollo Graph QL Client 的默认标题,我根本无法在文档中找到任何内容。因此,在我的 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()
});

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

必须有一些更简单的方法。有什么建议么

标签: reactjsreduxgraphqlapollo

解决方案


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". 这将应用于使用此客户端的所有查询。但是,我也在传播选项,因此任何出现options.headersfetch标题都将通过。

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

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

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

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

结果如下所示: 自定义标头正在通过,耶!


推荐阅读