GitHub的新GraphQL API需要使用 token 作为以前的版本进行身份验证。那么,如何在Apollo-Client的HttpLink中添加“Header”信息呢?

const client = new ApolloClient({
  link: new HttpLink({ uri: 'https://api.github.com/graphql' }),
  cache: new InMemoryCache()
});

最佳答案

您可以使用apollo-link-context定义授权 header ,检查the header section

将阿波罗客户端用于Github API的完整示例为:

import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';

const token = "YOUR_ACCESS_TOKEN";

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : null,
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(new HttpLink({ uri: 'https://api.github.com/graphql' })),
  cache: new InMemoryCache()
});

client.query({
  query: gql`
    query ViewerQuery {
      viewer {
        login
     }
    }
  `
})
  .then(resp => console.log(resp.data.viewer.login))
  .catch(error => console.error(error));

关于javascript - 使用Apollo-Client对GitHub API v4进行身份验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47992725/

10-12 04:12