【问题标题】:Authentication for GitHub API v4 with Apollo-Client使用 Apollo-Client 对 GitHub API v4 进行身份验证
【发布时间】:2018-06-08 03:08:25
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs github-api apollo apollo-client


    【解决方案1】:

    更新 - 2021 年 10 月

    使用@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));
    

    原帖 - 2017 年 12 月

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

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

    【讨论】:

      猜你喜欢
      • 2013-08-03
      • 1970-01-01
      • 2015-09-10
      • 2019-08-17
      • 2017-11-24
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多