Authentication for GitHub API v4 with Apollo-Client

断了今生、忘了曾经 提交于 2019-12-23 23:37:16

问题


GitHub's new GraphQL API requires authentication with a token as the previous version. So, how do we add a 'Header' information into the HttpLink inside Apollo-Client?

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

回答1:


You can define authorization header using apollo-link-context, check the header section

A complete example for using apollo-client for Github API would be :

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));


来源:https://stackoverflow.com/questions/47992725/authentication-for-github-api-v4-with-apollo-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!