2017-12-27 20 views
1

GitHub的新GraphQL API需要使用令牌作爲先前版本進行驗證。那麼,我們如何在Apollo-Client裏添加一個'Header'信息到HttpLink?通過Apollo客戶端驗證GitHub API v4

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

回答

2

您可以定義使用apollo-link-context授權頭,檢查the header section

一個完整的例子,使用阿波羅 - 客戶端API Github上會是:

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