【问题标题】:Update header after initializing ApolloProvider初始化 ApolloProvider 后更新标头
【发布时间】:2020-08-06 21:56:41
【问题描述】:

我使用 uploadLink 来设置用于向我的 Apollo 服务器发出请求的标头(请参见下面的代码)。但是,在我登录后,我想重置标头,因为在 Apollo Provider 初始化期间,标头中包含的“organizationid”在本地存储中尚不可用。登录后,我只从 Apollo 服务器的查询中获取“organizationid”。

const {othertoken} = queryString.parse(window.location.search)

const header = {
    Authorization: ' Bearer ' + localStorage.getItem('accounts:accessToken'),
    othertoken,
    organizationid: localStorage.getItem('organizationId')
}

const uri = CONFIG.graphQLServerTest

const uploadLink = createUploadLink({uri, headers: header})
const cache = new InMemoryCache()

const apolloClient = new ApolloClient({
    cache,
    resolvers: merge(dashboardStore.resolvers, collectionStore.resolvers, templateStore.resolvers, documentStore.resolvers) as any,
    link: ApolloLink.from([errorLink, uploadLink])
})


cache.writeData({data: collectionStore.defaults})
cache.writeData({data: dashboardStore.defaults})
cache.writeData({data: documentStore.defaults})
cache.writeData({data: templateStore.defaults})

const accountsGraphQL = new GraphQLClient({graphQLClient: apolloClient})
const accountsClient = new AccountsClient({}, accountsGraphQL)
const accountsPassword = new AccountsClientPassword(accountsClient)

export {accountsClient, accountsGraphQL, accountsPassword, apolloClient}

在我将其保存在本地存储中后,我需要在所有查询中发送到服务器的每个查询中都包含“organizationid”。为此,我需要在本地存储中保存“organizationid”后重新初始化标头。有没有办法做到这一点?

我想避免在我的所有查询中包含“organizationid”作为查询参数。

【问题讨论】:

  • 就像登录后的token一样?在阿波罗文档中检查身份验证
  • 谢谢,我尝试使用 authLink 但它似乎干扰了我使用的身份验证库 - 这意味着我使用 authLink 设置的上下文没有到达服务器上。
  • 使用链接是包含动态数据标题的正确方法 - 调试它...准备在代码和框上工作minimal reproducible example ...创建下一个/另一个解决方法不是正确的方法...它应该工作github.com/apollographql/apollo-client/issues/3302
  • 谢谢。我现在能够使用 setContext 解决它!非常感谢!!!

标签: graphql react-apollo apollo-client


【解决方案1】:

我能够通过使用 setContext 创建的 authLink 解决问题:

const authLink = setContext((_, {headers}) => {
    return {
        headers: {
            ...headers,
            organizationid: localStorage.getItem('organizationId')
        }
    }
});

【讨论】:

  • 您忘记包含现有标题 (...headers,) - 这样,您将只用一个替换它们
  • 我不明白为什么,但出于某种原因,在我的情况下,标题似乎没有被覆盖(我猜是因为我的 auth 库 --> accounts-js 会处理它)。谢谢!
  • 我现在还是改变了它,虽然它似乎对我的情况没有影响
猜你喜欢
  • 2019-09-18
  • 2012-07-12
  • 2017-02-15
  • 2014-03-21
  • 1970-01-01
  • 2015-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多