谢谢大家阅读我的问题。标题正是我想知道的。 希望它不会花费您太多时间。
答案 0 :(得分:3)
一些最常见的graphql客户是graphql.js和apollo-client。您也可以使用流行的request模块。 graphql API是https://api.github.com/graphql上的单个POST端点,其JSON主体由query
字段和variables
字段组成(如果查询中有变量)
const graphql = require('graphql.js');
var graph = graphql("https://api.github.com/graphql", {
headers: {
"Authorization": "Bearer <Your Token>",
'User-Agent': 'My Application'
},
asJSON: true
});
graph(`
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
createdAt
}
}
`, {
name: "linux",
owner: "torvalds"
}).then(function(response) {
console.log(JSON.stringify(response, null, 2));
}).catch(function(error) {
console.log(error);
});
fetch = require('node-fetch');
const ApolloClient = require('apollo-client').ApolloClient;
const HttpLink = require('apollo-link-http').HttpLink;
const setContext = require('apollo-link-context').setContext;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
const gql = require('graphql-tag');
const token = "<Your 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 repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
createdAt
}
}
`,
variables: {
name: "linux",
owner: "torvalds"
}
})
.then(resp => console.log(JSON.stringify(resp.data, null, 2)))
.catch(error => console.error(error));
const request = require('request');
request({
method: 'post',
body: {
query: `
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
createdAt
}
} `,
variables: {
name: "linux",
owner: "torvalds"
}
},
json: true,
url: 'https://api.github.com/graphql',
headers: {
Authorization: 'Bearer <Your Token>',
'User-Agent': 'My Application'
}
}, function(error, response, body) {
if (error) {
console.error(error);
throw error;
}
console.log(JSON.stringify(body, null, 2));
});