gpt4 book ai didi

javascript - 使用 Apollo-Client 对 GitHub API v4 进行身份验证

转载 作者:行者123 更新时间:2023-11-29 16:39:22 25 4
gpt4 key购买 nike

与之前的版本一样,GitHub 的新 GraphQL API 需要使用 token 进行身份验证。那么,我们如何在 Apollo-Client 内的 HttpLink 中添加“ header ”信息呢?

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定义授权 header ,请检查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));

关于javascript - 使用 Apollo-Client 对 GitHub API v4 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47992725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com