Mas*_*iar 2 node.js express graphql
我最近为我的 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
});
Run Code Online (Sandbox Code Playgroud)
如何在 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));
Run Code Online (Sandbox Code Playgroud)
此解决方案取自此处
| 归档时间: |
|
| 查看次数: |
5907 次 |
| 最近记录: |