如何从 Node.js/Express 服务器调用 GraphQL API? [英] How to call GraphQL API from Node.js/Express server?

查看:25
本文介绍了如何从 Node.js/Express 服务器调用 GraphQL API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近为我的 Express 服务器实现了一个架构和一些解析器.我通过 /graphql 成功测试了它们,现在我想调用我在从 REST API 访问时实现的查询,如下所示:

//[...]//模式和根正确实施和工作app.use('/graphql', graphqlHTTP({架构:架构,根值:根,图形:真实,}));//我启动服务器app.listen(port, () => {console.log('我们住在' + 端口);});//许多GET处理程序之一app.get("/mdc/all/:param", function(req, res) {//在这里调用(参数化的)查询之一//响应JSON结果});

如何在 GET 处理程序中调用我用 GraphQL 定义的查询?我如何向他们传递参数?

谢谢!

解决方案

基本上你可以使用 http post 方法从 GraphQL API 中获取数据,但是这里使用 node-fetch 非常好的解决方案,来安装它:<块引用>

npm install node-fetch --save

使用它的代码是:

const fetch = require('node-fetch');const accessToken = 'your_access_token_from_github';常量查询 = `询问 {存储库(所有者:isaacs",名称:github"){问题(状态:关闭){总数}}}`;获取('https://api.github.com/graphql',{方法:'POST',正文:JSON.stringify({query}),标题:{'授权':`Bearer ${accessToken}`,},}).then(res => res.text()).then(body => console.log(body))//{"data":{"repository":{"issues":{"totalCount":247}}}}.catch(error => console.error(error));

此解决方案取自此处

I recently implemented a schema and some resolvers for my Express server. I tested them successfully through /graphql and now I would like to call the queries I implemented when accessing from a REST API, like so:

//[...]
//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
});

How can I call the queries I defined with GraphQL inside my GET handlers? How do I pass parameters to them?

Thank you!

解决方案

Basically you can just use http post method to fetch the data from a GraphQL API, but here very nice solution using node-fetch , to install it:

npm install node-fetch --save

and the code to use it is:

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));

this solution was taken from here

这篇关于如何从 Node.js/Express 服务器调用 GraphQL API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆