【问题标题】:Unable to set authorization header using Apollo's setContext()无法使用 Apollo 的 setContext() 设置授权标头
【发布时间】:2020-10-14 21:23:36
【问题描述】:

所以我试图根据他们网站上的文档将授权标头传递给 Apollo。

https://www.apollographql.com/docs/react/networking/authentication/?fbclid=IwAR17YAJ0VA5G8InmAJ_PxcukXKNQxFLFI8aeT4oB7wYE3DjWNaB_F67__zs

但是,当我尝试在我的服务器上登录 request.headers 时,我看不到授权属性。接下来,我通过在其中添加console.log() 来检查函数setContext() 是否正在运行,发现它没有运行。

const httpLink = new HttpLink({ uri: 'http://localhost:4000' });

const authLink = setContext((request, { headers }) => {
  const token = localStorage.getItem('library-user-token')
  console.log(token)    //doesn't log at all
  return ({
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : null,
    }
  })
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

【问题讨论】:

  • 我的项目中有几乎相同的代码,并且可以正常工作。您是否将客户传递给您的ApolloProvider
  • SDKFSISDFIKOSFO。非常感谢老兄,那是我没有做的事
  • 酷。乐意效劳。我添加了我的评论作为答案。 :)

标签: apollo apollo-client apollo-server


【解决方案1】:

我的项目中有几乎相同的代码,并且可以正常工作。您是否将客户端传递给您的ApolloProvider

【讨论】:

    猜你喜欢
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2020-02-21
    • 2021-11-21
    • 2015-12-02
    • 1970-01-01
    • 2020-02-22
    相关资源
    最近更新 更多