Graphql 初始化提供程序后更新标头

Graphql 初始化提供程序后更新标头,graphql,react-apollo,apollo-client,Graphql,React Apollo,Apollo Client,我使用uploadLink来设置用于向Apollo服务器发出请求的头(参见下面的代码)。但是,在我登录之后,我想重置标头,因为标头中也包含“organizationid”,在Apollo Provider初始化期间,该ID在本地存储中尚不可用。我只在登录后通过查询从Apollo服务器获取“organizationid” const {othertoken} = queryString.parse(window.location.search) const header = { Auth

我使用uploadLink来设置用于向Apollo服务器发出请求的头(参见下面的代码)。但是,在我登录之后,我想重置标头,因为标头中也包含“organizationid”,在Apollo Provider初始化期间,该ID在本地存储中尚不可用。我只在登录后通过查询从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”保存到本地存储后,我需要在所有查询中发送到服务器的每个查询中包含该ID。为此,我需要在本地存储中保存“organizationid”后重新初始化标头。有办法做到这一点吗


我希望避免将“organizationid”作为查询参数包含到我的所有查询中。

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

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

就像登录后的令牌一样?检查apollo docsThanks中的auth,我尝试使用authLink,但它似乎干扰了我使用的身份验证库-这意味着我使用authLink设置的上下文没有到达服务器。使用链接是包含动态数据的标题的正确方法-取消错误。。。准备使用codesandbox。。。创建下一个/另一个解决方案不是正确的方法。。。应该有用的,谢谢。我现在可以使用setContext解决它了!谢谢!!!您忘了包括现有的头(
…头,
)-这样,您就只用一个头替换它们了。我不明白为什么,但在我的例子中,由于某种原因,头似乎没有被覆盖(我想是因为我的auth library-->accounts js处理了它)。谢谢我现在还是改变了它,虽然它似乎对我的情况没有影响