使用 Apollo-Client 对 GitHub API v4 进行身份验证

IT技术 javascript reactjs github-api apollo apollo-client
2021-05-13 00:24:08

GitHub 的新 GraphQL API 需要使用令牌进行身份验证,就像以前的版本一样。那么,我们如何在HttpLink里面添加一个'Header'信息Apollo-Client呢?

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

更新 - 10/2021

使用@apollo/clientgraphql包装:

import { 
  ApolloClient, 
  InMemoryCache, 
  gql, 
  HttpLink 
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context";

const token = "YOUR_TOKEN";

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: token ? `Token ${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));

原帖 - 12/2017

您可以使用定义授权标题apollo-link-context,检查标题部分

将 apollo-client 用于 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));