node.js - 如何从 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 定义的查询?如何将参数传递给他们?
谢谢!
解决方案
基本上你可以使用 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));
该解决方案取自此处
推荐阅读
- python - 将 PySpark 数据帧记录到 MLFlow 工件中
- python - Python3 - 如果另一个列表中的值足够接近,则平均一个列表中的值
- java - 调用 RMI 方法会释放同步锁吗?
- java - 如何在java中获取方法?
- mysql - SQL If field is '*' then select from another table
- javascript - 通过引用反应调用方法不起作用
- amazon-web-services - 为 S3 存储桶中的每个对象调用 lambda
- dynamics-crm - 有没有办法在网格顶部隐藏快速查找?
- c - ARDUINO:组合串行输入的所有字符
- c# - Tesseract 不读取单个值和某些值