简体   繁体   English

用节点查询graphql

[英]querying graphql with node

I am trying to query a graphQL endpoint but I can't figure out what I am doing wrong.我正在尝试查询 graphQL 端点,但我不知道我做错了什么。 How am I supposed to set up the graphQL object to pass over.我应该如何设置要传递的 graphQL 对象。 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()

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.基本上,您需要将 JSON 查询转换为字符串。 This is how I do it with the GitHub GraphQL API v4.这就是我使用 GitHub GraphQL API v4 的方式。

Here is the example using fetch.这是使用 fetch 的示例。 I think you don't need apollo client unless you really need it.我认为你不需要 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 } }' }),
})

I've found that the easiest way to do this is by using the Apollo Client library @apollo/client .我发现最简单的方法是使用Apollo 客户端@apollo/client You should note however that this library unfortunately makes the assumption that you're using React, and there's no vanilla JS client, but you can still import the classes you need from core and avoid any React dependencies.但是您应该注意,不幸的是,这个库假设您正在使用 React,并且没有 vanilla JS 客户端,但是您仍然可以从core导入所需的类并避免任何 React 依赖项。

import {
    ApolloClient,
    InMemoryCache,
    HttpLink
} from "@apollo/client/core"
// Use cross-fetch for Node versions lower than 18.
import fetch from 'cross-fetch'

const client = new ApolloClient({
    link: new HttpLink({ uri, fetch }),
    cache: new InMemoryCache(),
    name: "my client",
    version: "1.0.0",
    assumeImmutableResults: true
})

const query = gql`
    query Query {
        hello
    }
`
const response = await client.query({ query })

Also note that there used to be a bug with old versions of @apollo/client/core having an unnecessary React dependency, I'm using "@apollo/client": "^3.6.5" and don't have that issue.另请注意,旧版本的@apollo/client/core曾经存在一个错误,它具有不必要的 React 依赖项,我正在使用"@apollo/client": "^3.6.5"并且没有这个问题。

I'm not seeing graphql in your code at all. 我根本没有在你的代码中看到graphql。

Check this project to help your star: 检查此项目以帮助您的明星:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM