reactjs - Apollo GraphQL:更改默认标题 INSIDE React 子组件
问题描述
我正在尝试在一个反应组件中更改我的 Apollo Graph QL Client 的默认标题,但我根本无法在文档中找到任何内容。因此,在我的 index.js 中,我按照描述创建和链接我的客户端,并添加一个 JWT 令牌标头。但是如果我想更改我的 React 组件中的标题怎么办。例如,我想在 reauthenticate 时替换 Token。
在 Axios 中,您可以简单地对此进行操作。
axios.defaults.headers.common['Auth-Token'] = 'foo bar';
我怎样才能用 React Apollo 做这样的事情?这是我的 index.js 的重要部分
const httpLink = createHttpLink({
uri: 'https://somesecureapi',
});
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('token');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
我尝试导出客户端,然后将其导入组件创建一个新链接并更改旧链接,但这不起作用。
必须有一些更简单的方法。有什么建议么
解决方案
createHttpLink
接受fetch
选项,您可以在其中自定义您希望自己fetch
的行为方式。一个简单的实现可能如下所示:
import { ApolloProvider, graphql } from "react-apollo";
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloLink } from "apollo-link";
import { createHttpLink } from "apollo-link-http";
const customFetch = (uri, options) => {
return fetch(uri, {
...options,
headers: {
...options.headers,
"x-custom-header": "custom value"
}
});
};
const fetchLink = createHttpLink({
uri: "https://graphql-pokemon.now.sh",
fetch: customFetch
});
const client = new ApolloClient({
link: ApolloLink.from([fetchLink]),
cache: new InMemoryCache()
});
正如您在 中看到的customFetch
,我添加x-custom-header
了"custom value"
. 这将应用于使用此客户端的所有查询。但是,我也在传播选项,因此任何出现options.headers
的fetch
标题都将通过。
在我们的组件中,我们可以像这样传递额外的标头:
const WrappedPokemon = graphql(PokemonQuery, {
options: {
context: { headers: { "x-another-custom-header": "another custom value" } }
},
props: ({ data }) => ({
loading: data.loading,
pokemon: data.pokemon || {}
})
})(Pokemon);
与上面的不同,这个额外的标题只存在于这个查询中。
我在codesandbox中做了一个简单的实现,帮助大家理解实现。
推荐阅读
- npm - Vaadin 19:使用具有自己的 Vaadin 依赖项的 NPM 模块失败
- apple-m1 - 备注:增量编译已禁用:不兼容整个模块优化
- c# - 切换情况下的并行异步任务执行
- amazon-web-services - terraform 中的 aws_security_group_rule 嵌套 For_each 或动态计数
- spring-data-jpa - 在运行时为每个登录用户提供新数据源的 Spring Data JPA
- r - 根据另一个数据框的列名对行的顺序进行排序
- javascript - 如何在 redux 'useStore' 中存储简单变量并在另一个函数中调用?
- apache-spark - 检查 Spark 会话是否成功创建且无异常并准备好执行任务
- ios - 自定义 RPSystemBroadcastPickerView?
- javascript - 未捕获(承诺)错误:已使用 pdf-merger-js 模块结束