无法使用 Apollo 的 setContext() 设置授权 header

Unable to set authorization header using Apollo's setContext()

所以我试图根据他们网站上的文档向 Apollo 传递授权 header。

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

但是,当我尝试在我的服务器上登录 request.headers 时,我没有在服务器上看到授权 属性。接下来我通过在函数 setContext() 中放置一个 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