querying graphql with node

浪子不回头ぞ 提交于 2020-01-14 13:49:07

问题


I am trying to query a graphQL endpoint but I can't figure out what I am doing wrong. How am I supposed to set up the graphQL object to pass over. If I am trying to pass

{
  name {
     age
  }
}

How should I be wrapping this to get the correct response from the server? The full code I am currently working with is below

var http = require('http')
var qs = require('querystring')

var options = {
    hostname: 'url',
    method: 'POST',
    path: '/query'
}

var req = http.request(options, function(res){
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
    });
    res.on('end', function() {
        console.log('No more data in response.')
    })
})

var query = qs.stringify({data: {classes:{}}})


req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.write(query)
req.end()

回答1:


You can do it like this.

payload = {
    "query": `{
        name {
            age
        }
    }`
}
JSON.stringify(payload)

The name "query" might be different in your case. Basically, you need to convert the JSON query to string. This is how I do it with the GitHub GraphQL API v4.




回答2:


I'm not seeing graphql in your code at all.

Check this project to help your star:

https://github.com/graphql/express-graphql



来源:https://stackoverflow.com/questions/35811116/querying-graphql-with-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!