Apollo 客户端未将 headers 发送到 API 端点

Apollo Client not sending headers to API endpoint

我有一个 Apollo 客户端,这是我第一次尝试连接到 graphql 服务器。我似乎无法让它发送任何 headers...

我实例化 apollo 客户端的组件如下所示...

const cache = new InMemoryCache();

const stateLink = withClientState({ resolvers, cache, apolloState });
const httpLink = new HttpLink({
  uri: urls.graphqlServer + urls.graphqlEndpoint,
  options: {
    credentials: 'include',
    headers: {
      authorization: 'bearer token',
      'X-CSRF-Token': 'sakldjsalkj',
      'Custom-Header': 'my header'
    }
  }
});

const client = new ApolloClient({
  cache,
  link: ApolloLink.from([stateLink, httpLink]),
  connectToDevTools: true
});

window.__APOLLO_CLIENT__ = client;

return (
  <ApolloProvider client={client}>
    <Root />
  </ApolloProvider>
);

然后 headers 不包含我设置的任何内容...

:authority:localhost:8080
:method:OPTIONS
:path:/graphql
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:en-US,en;q=0.9,ko;q=0.8,zh-CN;q=0.7,zh;q=0.6
access-control-request-headers:content-type
access-control-request-method:POST
origin:http://localhost:8000
referer:http://localhost:8000/app
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36

知道如何解决这个问题吗?

您在错误的 "options" object 中添加了 headers 的选项。看看 docu.

当您将 apollo http link 更改为:

时它应该可以工作

....

const httpLink = new HttpLink({
  uri: urls.graphqlServer + urls.graphqlEndpoint,
  credentials: 'include',
  headers: {
    authorization: 'bearer token',
    'X-CSRF-Token': 'sakldjsalkj',
    'Custom-Header': 'my header'
  }
});

...