2017-12-27 9 views
1

Die neue GraphQL-API von GitHub erfordert die Authentifizierung mit einem Token als vorherige Version. Also, wie fügen wir eine 'Header' Informationen in den HttpLink innerhalb Apollo-Client?Authentifizierung für GitHub API v4 mit Apollo-Client

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

Antwort

2

können Sie Autorisierungsheader definieren apollo-link-context verwenden, prüfen the header section

Ein komplettes Beispiel für die Verwendung von apollo-Client für Github API wäre:

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