我正在尝试根据官方doc动态设置Apollo客户端的 header ,但我收到一个错误:
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;
更新
我正在添加 应用.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>);
}
我该如何解决这个问题?
最佳答案
Apollo usequery 有一个上下文选项,允许您动态更改或更新 header 对象的值。
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
关于javascript - 动态设置 Apollo 客户端 header 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61495727/