在React Native Apollo客户端中调用变异时如何传递附加标头?

时间:2019-09-24 05:20:32

标签: react-native react-apollo

在React本机apollo客户端中调用变异时如何传递附加标头?

我的客户在这里:

import { HttpLink } from 'apollo-link-http';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

const makeApolloClient = (token) => {
  // create an apollo link instance, a network interface for apollo client
  const link = new HttpLink({
    uri: 'http://x.x.x.x:xxxx/xxxx',
    headers: {
     Authorization: `Bearer ${token}`
    },
  });
  // create an inmemory cache instance for caching graphql data
  const cache = new InMemoryCache();
  // instantiate apollo client with apollo link instance and cache instance
  const client = new ApolloClient({
    link,
    cache
  });
  return client;
};
export default makeApolloClient;

如果在使用查询或突变时需要向同一客户端添加其他标头,该怎么办?

是否可以使用“ apollo-link-context ”?

2 个答案:

答案 0 :(得分:3)

这可以通过接收在mutation/query中设置的上下文来完成。

在突变中设置自定义标头

const [addTodo] = useMutation(ADD_TODO, {
    refetchQueries: [{ query: GET_TODO }], //updating the list of todos list after adding
    context: {
      headers: {
        "x-custom-component-add": "kkk-add",
        "x-origin-server": "pure-react"
      }
    }
  });

在mutation/query中设置的中间件中接收上下文

const httpLink = new HttpLink({ uri: "https://sxewr.sse.codesandbox.io/" });

const authMiddleware = new ApolloLink((operation, forward) => {
  const customHeaders = operation.getContext().hasOwnProperty("headers") ? operation.getContext().headers : {};
  console.log(customHeaders);
  operation.setContext({
    headers: {
      ...customHeaders
      //we can also set the authorization header
      // authorization: localStorage.getItem('jjjjjj'),
    }
  });
  return forward(operation);
});

最终通过Apoolo Client中的中间件

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: from([authMiddleware, httpLink])
});

这是有效的 sample

https://codesandbox.io/s/passing-custom-header-in-graphql-mutation-query-l332g?file=/src/index.js

自定义标题看起来像这样 enter image description here

答案 1 :(得分:0)

您尚未指定React版本,但是假设您使用Hooks,请按照以下步骤进行操作。如果您不使用挂钩,请使用左上方的下拉菜单更改此答案底部的链接的文档版本。

查询的地方:

const GET_USER = gql`
    query getUser{
     node {
       name
       age
     }
   }
`;

您将要使用useQuery挂钩运行查询:

const { loading, error, data } = useQuery(GET_USER, {
    context: {
        headers: {
            "Content-Type": "application/json"
        }
    }
})

文档:

您可以在这里找到每个文档:  -UseQuery:https://www.apollographql.com/docs/react/essentials/queries/  -上下文标题:https://www.apollographql.com/docs/link/links/http/#passing-context-per-query