如何调用从的Node.js / Express服务器GraphQL API?(How to call

2019-10-30 01:31发布

我最近实施的模式和一些解析器我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定义的查询? 我如何传递参数?

谢谢!

Answer 1:

基本上,你可以使用HTTP POST方法来获取从GraphQL API的数据,但在这里很不错的解决方案使用节点取,进行安装:

NPM安装节点取--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));

该溶液取自这里



Answer 2:

我用阿波罗并直接上执行的查询/graphql通过POST从前端。



文章来源: How to call GraphQL API from Node.js/Express server?