首页 > 解决方案 > 如何从 Node.js/Express 服务器调用 GraphQL API?

问题描述

我最近为我的 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 定义的查询?如何将参数传递给他们?

谢谢!

标签: node.jsexpressgraphql

解决方案


基本上你可以使用 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));

该解决方案取自此处


推荐阅读