在 React Native apollo 客户端中调用突变时如何传递附加标头? [英] How to pass Additional Header when calling mutation in React native apollo client?

查看:49
本文介绍了在 React Native apollo 客户端中调用突变时如何传递附加标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 React Native apollo 客户端调用突变时传递额外的 Header ?

How to pass Additional Header when calling mutation in React native apollo client ?

我的客户在这里:

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;

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

If i need to add additional header to this same client when using query or mutation how can i do it ?

是否可以使用apollo-link-context"?

推荐答案

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

You haven't specified your React version however assuming you use Hooks you do it as follows. If you aren’t using hooks change the doc version for the links at the bottom of this answer using the drop down in the top left.

您在哪里查询:

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

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

You’ll want to run a query with the useQuery hook:

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

文档:

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

You can find the docs for each here: - UseQuery: https://www.apollographql.com/docs/react/essentials/queries/ - Context Headers: https://www.apollographql.com/docs/link/links/http/#passing-context-per-query

这篇关于在 React Native apollo 客户端中调用突变时如何传递附加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆