使用 Apollo-Client 对 GitHub API v4 进行身份验证 [英] Authentication for GitHub API v4 with Apollo-Client

查看:26
本文介绍了使用 Apollo-Client 对 GitHub API v4 进行身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

更新 - 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 的完整示例是:

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

这篇关于使用 Apollo-Client 对 GitHub API v4 进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆