通过Apollo客户端验证GitHub API v4

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

});

回答:

您可以定义使用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));

以上是 通过Apollo客户端验证GitHub API v4 的全部内容, 来源链接: utcz.com/qa/265207.html

回到顶部