GraphQL.JS 文档
GraphQL 客户端

由于 GraphQL API 比 REST API 具有更多底层结构,因此有更强大的客户端(例如 Relay)可以自动处理批处理、缓存和其他功能。但你不需要复杂的客户端来调用 GraphQL 服务器。使用 graphql-http,你只需向安装 GraphQL 服务器的端点发送 HTTP POST 请求,将 GraphQL 查询作为 JSON 负载中的 query 字段传递。

¥Since a GraphQL API has more underlying structure than a REST API, there are more powerful clients like Relay which can automatically handle batching, caching, and other features. But you don’t need a complex client to call a GraphQL server. With graphql-http, you can just send an HTTP POST request to the endpoint you mounted your GraphQL server on, passing the GraphQL query as the query field in a JSON payload.

例如,假设我们在 http://localhost:4000/graphql 上安装了 GraphQL 服务器(如 运行 Express GraphQL 服务器 的示例代码所示),并且我们想要发送 GraphQL 查询 { hello }。我们可以使用 curl 从命令行执行此操作。如果将其粘贴到终端中:

¥For example, let’s say we mounted a GraphQL server on http://localhost:4000/graphql as in the example code for running an Express GraphQL server, and we want to send the GraphQL query { hello }. We can do this from the command line with curl. If you paste this into a terminal:

curl -X POST \
-H "Content-Type: application/json" \
-d '{"query": "{ hello }"}' \
http://localhost:4000/graphql

你应该看到以 JSON 形式返回的输出:

¥You should see the output returned as JSON:

{"data":{"hello":"Hello world!"}}

如果你更喜欢使用图形用户界面发送测试查询,则可以使用 GraphiQLInsomniaPostman 等客户端。

¥If you prefer to use a graphical user interface to send a test query, you can use clients such as GraphiQL, Insomnia, and Postman.

从浏览器发送 GraphQL 也很简单。打开 http://localhost:4000/graphql,打开开发者控制台,然后粘贴:

¥It’s also simple to send GraphQL from the browser. Open up http://localhost:4000/graphql, open a developer console, and paste in:

fetch("/graphql", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  body: JSON.stringify({ query: "{ hello }" }),
})
  .then(r => r.json())
  .then(data => console.log("data returned:", data))

你应该看到返回的数据,并记录在控制台中:

¥You should see the data returned, logged in the console:

data returned: Object { hello: "Hello world!" }

在此示例中,查询只是一个硬编码字符串。随着你的应用变得更加复杂,并且你添加了采用 传递参数 中所述的参数的 GraphQL 端点,你将希望使用客户端代码中的变量构建 GraphQL 查询。你可以通过在查询中包含以美元符号为前缀的关键字并在负载上传递额外的 variables 字段来实现此目的。

¥In this example, the query was just a hardcoded string. As your application becomes more complex, and you add GraphQL endpoints that take arguments as described in Passing Arguments, you will want to construct GraphQL queries using variables in client code. You can do this by including a keyword prefixed with a dollar sign in the query, and passing an extra variables field on the payload.

例如,假设你正在运行 传递参数 的示例服务器,其结构为

¥For example, let’s say you’re running the example server from Passing Arguments that has a schema of

type Query {
  rollDice(numDice: Int!, numSides: Int): [Int]
}

你可以使用以下代码从 JavaScript 访问此内容:

¥You could access this from JavaScript with the code:

var dice = 3
var sides = 6
var query = /* GraphQL */`query RollDice($dice: Int!, $sides: Int) {
  rollDice(numDice: $dice, numSides: $sides)
}`
 
fetch("/graphql", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "application/json",
  },
  body: JSON.stringify({
    query,
    variables: { dice, sides },
  }),
})
  .then(r => r.json())
  .then(data => console.log("data returned:", data))

对变量使用此语法是一个好主意,因为它可以自动防止由于转义而导致的错误,并且可以更轻松地监视服务器。

¥Using this syntax for variables is a good idea because it automatically prevents bugs due to escaping, and it makes it easier to monitor your server.

一般来说,设置像 Relay 这样的 GraphQL 客户端会花费更多时间,但随着应用的增长获得更多功能是值得的。你可能希望一开始仅使用 HTTP 请求作为底层传输层,并随着应用变得更加复杂而切换到更复杂的客户端。

¥In general, it will take a bit more time to set up a GraphQL client like Relay, but it’s worth it to get more features as your application grows. You might want to start out just using HTTP requests as the underlying transport layer, and switching to a more complex client as your application gets more complex.

此时,你可以使用 GraphQL 为接收单个字符串的 API 编写客户端和服务器。要做得更多,你需要 学习如何使用其他基本数据类型

¥At this point you can write a client and server in GraphQL for an API that receives a single string. To do more, you will want to learn how to use the other basic data types.