如何从Node.js/Express服务器调用GraphQL API?

3

最近我在我的Express服务器上实现了一些模式和解析器。我通过/graphql成功地对它们进行了测试,现在我想在从REST API访问时调用我实现的查询,如下所示:

//[...]
//schema and root correctly implemented and working
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

//I start the server
app.listen(port, () => {
  console.log('We are live on ' + port);
});

//one of many GET handlers
app.get("/mdc/all/:param", function(req, res) {
    //call one of the (parametrized) queries here
    //respond with the JSON result
});

我应该如何在我的GET处理程序中调用使用GraphQL定义的查询?我如何向它们传递参数?
谢谢!

你想从那个路由返回什么? - Anthony Garcia-Labiad
现在还没有,我想返回一些JSON,其中包含查询结果,并使用AXAJ从前端检索它。 - Masiar
我最终使用了Apollo Client库来完成这个任务。以下是具体步骤。https://dev59.com/FJTfa4cB1Zd3GeqPVMPz#72534090 - Mig82
2个回答

8

基本上,您可以使用HTTP POST方法从GraphQL API获取数据,但是这里有一个非常好的解决方案,使用node-fetch,安装它:

npm install node-fetch --save

并且使用它的代码如下:

const fetch = require('node-fetch');

const accessToken = 'your_access_token_from_github';
const query = `
  query {
    repository(owner:"isaacs", name:"github") {
      issues(states:CLOSED) {
        totalCount
      }
    }
  }`;

fetch('https://api.github.com/graphql', {
  method: 'POST',
  body: JSON.stringify({query}),
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
}).then(res => res.text())
  .then(body => console.log(body)) // {"data":{"repository":{"issues":{"totalCount":247}}}}
  .catch(error => console.error(error));

这个解决方案源自这里


3
您可以使用 graphql-request
import { request, GraphQLClient } from 'graphql-request'

// Run GraphQL queries/mutations using a static function
request(endpoint, query, variables).then((data) => console.log(data))

// ... or create a GraphQL client instance to send requests
const client = new GraphQLClient(endpoint, { headers: {} })
client.request(query, variables).then((data) => console.log(data))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接