How to call GraphQL API from Node.js/Express serve

2019-09-02 06:35发布

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!

2条回答
Summer. ? 凉城
2楼-- · 2019-09-02 07:05

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

查看更多
我只想做你的唯一
3楼-- · 2019-09-02 07:10

I used Apollo and performed queries directly on /graphql through POST from the front-end.

查看更多
登录 后发表回答