5

我正在尝试查询 graphQL 端点,但我不知道我做错了什么。我应该如何设置要传递的 graphQL 对象。如果我想通过

{
  name {
     age
  }
}

我应该如何包装它以从服务器获得正确的响应?我目前正在使用的完整代码如下

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()
4

2 回答 2

1

你可以这样做。

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

在您的情况下,名称“查询”可能会有所不同。基本上,您需要将 JSON 查询转换为字符串。这就是我使用 GitHub GraphQL API v4 的方式。

于 2017-11-25T10:31:51.250 回答
0

这是使用 fetch 的示例。我认为你不需要 apollo 客户端,除非你真的需要它。

require('isomorphic-fetch');

fetch('https://api.example.com/graphql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'authorization': `Bearer ${token}`,
      },
      body: JSON.stringify({ query: '{ name { age } }' }),
})
于 2020-06-06T12:15:57.967 回答