Apollo GraphQL:在 React 子组件中更改默认标头

Jan*_*utz 1 apollo reactjs graphql redux

我想改变我的阿波罗图QL客户端的默认头INSIDE一个反应成分,我根本不能设法找到的文档任何东西。因此,在我的 index.js 中,我按照描述创建并链接了我的客户端,并添加了一个 JWT 令牌标头。但是如果我想更改我的 React 组件中的标头怎么办。例如,我想在重新验证时替换令牌。

在 Axios 中,你可以简单地用它做一些事情。

axios.defaults.headers.common['Auth-Token'] = 'foo bar';
Run Code Online (Sandbox Code Playgroud)

我怎么能用 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()
});
Run Code Online (Sandbox Code Playgroud)

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

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

Jac*_*yef 6

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()
});
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

结果如下所示: 自定义标头正在传递,是的!