react-native - 动态设置 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>);
}
我该如何解决这个问题?
解决方案
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
推荐阅读
- grouping - 遗传算法:在不知道确切组数的情况下对学生进行分组
- python - 用一列合并两个 DF 部分相似
- python - `pip install --upgrade pip` 在 Windows 虚拟环境中失败,“访问被拒绝”
- react-native - 解码从使用 react-native-camera 扫描的 PDF417 条码返回的二进制数据
- types - 语言的程序员是否看不到静态和动态类型的选择?
- kubernetes - 需要将部署名称传递给相关 pod
- excel - 如何使用查找功能
- javascript - 如何正确等待 Selenium 直到滚动列表?
- javascript - 如何匹配重复的布尔搜索字符串模式
- ssl - traefik 1.7.X - 在 access.log 中记录 TLS 版本