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

Ras*_*eed 5 react-native react-apollo

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

如果我在使用查询或变异时需要向同一个客户端添加额外的标头,我该怎么做?

阿波罗链接上下文”有可能吗?

Lac*_*ung 10

您还没有指定您的 React 版本,但是假设您使用 Hooks,您可以按如下方式进行操作。如果您不使用钩子,请使用左上角的下拉菜单更改此答案底部链接的文档版本。

您在哪里查询:

const GET_USER = gql`
    query getUser{
     node {
       name
       age
     }
   }
`;
Run Code Online (Sandbox Code Playgroud)

您需要使用 useQuery 钩子运行查询:

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

文档:

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


Ank*_*arg 6

这可以通过接收突变/查询中设置的上下文来完成。

在突变中设置自定义标头

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

接收在突变/查询中设置的中间件中的上下文

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

最后在Apoolo Client中传递中间件

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

这是工作示例

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

自定义标题看起来像这样 在此输入图像描述