首页 > 解决方案 > 动态设置 Apollo 客户端标头不起作用

问题描述

我正在尝试根据官方文档动态设置 Apollo 客户端的标头,但出现错误:

    TypeError: (0 , _apollo.default) is not a function

这是我的apollo.js

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { AsyncStorage } from 'react-native';

const httpLink = createHttpLink({
    uri: 'http://192.168.2.4:8000/api/',
});

const authLink = setContext((_, { headers }) => {
    const token = AsyncStorage.getItem('token');

    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : "",
        }
    }
});

const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
});

export default client; 

更新

我正在添加App.js

import { ApolloProvider } from 'react-apollo';
import Routes from './app/config/routes';
import makeApolloClient from './app/config/apollo';

export default function App() {
  const client = makeApolloClient();

  return (
    <ApolloProvider client={client}>
      <Routes />
    </ApolloProvider>);
}

我该如何解决这个问题?

标签: react-nativegraphql

解决方案


Apollo usequery 有一个上下文选项,允许您动态更改或更新标头对象的值。

import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  cache: new InMemoryCache(),
  uri: "/graphql"
});

client.query({
  query: MY_QUERY,
  context: {
    // example of setting the headers with context per operation
    headers: {
      special: "Special header value"
    }
  }
});

上面的代码是从 Apollo 文档中复制的。要了解更多信息,请查看 https://www.apollographql.com/docs/react/networking/advanced-http-networking/#overriding-options


推荐阅读